Timer and TimerTask - how to reschedule Timer from within TimerTask run

倾然丶 夕夏残阳落幕 提交于 2019-12-14 03:53:42

问题


basically what I want to do is to make a Timer that runs a specific TimerTask after x seconds, but then the TimerTask can reschedule the Timer to do the task after y seconds. Example is below, it gives me an error "Exception in thread "Timer-0" java.lang.IllegalStateException: Task already scheduled or cancelled" on line where I try to schedule this task in TimerTask run.

import java.util.Timer;
import java.util.TimerTask;

public class JavaReminder {

    public JavaReminder(int seconds) {
        Timer timer = new Timer();  
        timer.schedule(new RemindTask(timer, seconds), seconds*2000);
    }

    class RemindTask extends TimerTask {
        Timer timer;
        int seconds;
        RemindTask(Timer currentTimer, int sec){
            timer = currentTimer;
            seconds = sec;
        }

        @Override
        public void run() {
            System.out.println("ReminderTask is completed by Java timer");
            timer = new Timer(); 
            timer.schedule(this, seconds*200);
            System.out.println("scheduled");
        }
    }

    public static void main(String args[]) {
        System.out.println("Java timer is about to start");
        JavaReminder reminderBeep = new JavaReminder(2);
        System.out.println("Remindertask is scheduled with Java timer.");
    }
}

回答1:


Use new RemindTask instead of existing one.

It should be

timer.schedule(new RemindTask(timer, seconds), seconds*200);

instead of

timer.schedule(this, seconds*200);


来源:https://stackoverflow.com/questions/25001052/timer-and-timertask-how-to-reschedule-timer-from-within-timertask-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!