Jack Love
Jack Love

Reputation: 726

Java: Run Script After Timed Interval

How do you activate or run a loop every tenth of a second? I want to run some script after an amount of time has passed.

Run a script every second or something like that. (notice the bolded font on every)

Upvotes: 0

Views: 671

Answers (3)

Bozho
Bozho

Reputation: 597016

Since Java 1.5:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new RepeatedTask(), 0, 100, TimeUnit.MILLISECONDS);

and

private class RepeatedTask implements Runnable {
    @Override
    public void run() {
        // do something here
    }
}

(remember to shotdown() your executor when finished)

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272217

You can use a TimerTask. e.g.

    timer = new Timer();
    timer.schedule(new RemindTask(), seconds*1000);

You simply need to define a Runnable. You don't have to worry about defining/scheduling threads etc. See the Timer Javadoc for more info/options (and Quartz if you want much more complexity and flexibility)

Upvotes: 3

Edwin Buck
Edwin Buck

Reputation: 70909

You sleep.

Check out Thread.sleep() but be warned that you probably really don't want your whole program to sleep, so you might wish to create a thread to explicitly contain the loop and it's sleeping behavior.

Note that sleep only delays for a number of milliseconds; and, that number is not a perfect guarantee. If you need better time resolution you will have to use System.currentTimeMillis() and do the "time math" yourself. The most typical scenario is when you run something and you want it to run ever minute. The time the script runs must be captured by grabbing System.currentTimeMillis() before and after the script, and then you would need to sleep the remaining 1000 - scriptRunTime milliseconds.

Upvotes: 0

Related Questions