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 ev开发者_运维技巧ery second or something like that. (notice the bolded font on every)
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)
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)
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.
精彩评论