[英]Timer and TimerTask - 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. 基本上我想做的是制作一个在x秒后运行特定TimerTask的Timer,但是TimerTask可以重新安排Timer在y秒后执行任务。 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.
示例如下,它给出了一个错误“线程中的异常”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.");
}
}
Use new RemindTask
instead of existing one. 使用新的
RemindTask
而不是现有的。
It should be 它应该是
timer.schedule(new RemindTask(timer, seconds), seconds*200);
instead of 代替
timer.schedule(this, seconds*200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.