基本上我想做的是在x秒后制作一个运行特定TimerTask的Timer,但是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.");
}
}
答案 0 :(得分:4)
使用新的RemindTask
代替现有的。{/ p>
应该是
timer.schedule(new RemindTask(timer, seconds), seconds*200);
而不是
timer.schedule(this, seconds*200);