Ariyan
Ariyan

Reputation: 15168

schedule periodic task at a fixed duration after previous one finished in java

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?

Upvotes: 0

Views: 2444

Answers (2)

JB Nizet
JB Nizet

Reputation: 692161

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.

Upvotes: 4

Ingo Kegel
Ingo Kegel

Reputation: 48105

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);
}

Upvotes: 2

Related Questions