如何从TimerTask运行中重新安排Timer

基本上我想要做的是使一个Timer在x秒后运行特定的TimerTask,但是然后TimerTask可以重新安排Timer在y秒后执行任务。 示例如下,它给我一个错误“线程中的异常”Timer-0“java.lang.IllegalStateException:任务已经调度或取消”在我尝试在TimerTask运行中调度此任务的线上。

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

使用新的RemindTask而不是现有的。

它应该是

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

代替

timer.schedule(this, seconds*200);
链接地址: http://www.djcxy.com/p/74923.html

上一篇: how to reschedule Timer from within TimerTask run

下一篇: Rescheduling Timer in android