简体   繁体   中英

Java - Recursively schedule a timer task

Is there a way to run a timer task only after the method completes. The method could take 10 seconds but the timer is set to run every 5 seconds. I want it to run again only after the 10 seconds are up.

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            longRunningMethod();
            timer.schedule(task, 0, 5000);
        }
    };
    timer.schedule(task, 0, 10000);

You can use ScheduledExecutorService which has a scheduleWithFixedDelay() method which does exactly that.

"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."

So you could do

ExecutorService.newScheduledExecutor()
    .submit(this::longRunningMethod, 0, 1000, ChronoUnit.MILLIS);

Removing the timer.schedule(task, 0, 5000); call will give you behavior you desire.

Your call of timer.schedule(task, 0, 10000);schedules repeating tasks every ten seconds.

You need to schedule one-shot timer tasks and create new TimerTask instance every time.

class MyTimerTask extends TimerTask {
    private final Timer timer;
    private final long nextScheduleDelay;

    MyTimerTask(Timer timer, long nextScheduleDelay) {
        this.timer = timer;
        this.nextScheduleDelay = nextScheduleDelay;
    }

    @Override
    public void run() {
        longRunningMethod();
        timer.schedule(new MyTimerTask(timer, nextScheduleDelay), nextScheduleDelay);
    }
}

Timer timer = new Timer();
timer.schedule(new MyTimerTask(timer, 1000), 0);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM