how to reschedule Timer from within TimerTask run

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

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);
链接地址: http://www.djcxy.com/p/74924.html

上一篇: 自定义字体和XML布局(Android)

下一篇: 如何从TimerTask运行中重新安排Timer