I wrote an application that runs a thread periodically using Timer.scheduleAtFixedRate
like this:
this.ExtractorTimer=new Timer();
this.ExtractorTimer.scheduleAtFixedRate(new java.util.TimerTask() {
public void run() {
...
}
},0, 120000);
This runs next thread exactly after a specific time (for example 2 minutes) and if current thread was not finished, it runs next one just after current one finished.
I need that next thread run after a duration of time after current thread finished .
How can I do that?
Use ScheduledExecutorService
's scheduleWithFixedDelay
method, which does exactly that. You may obtain an instance of such an executor service thanks to the Executors
factory class. This class is the replacement for Timer, which has some deficiencies.
Instead of using scheduleAtFixedRate
you could schedule the next execution after the task is completed:
public void initTimer() {
Timer timer = new Timer();
scheduleTask(timer);
}
private void scheduleTask(final Timer timer) {
timer.schedule(new TimerTask() {
public void run() {
// perform task here
scheduleTask(timer);
}
}, 120000);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.