Java Timer
我正在尝试使用计时器来计划在应用程序中定期发生事件。但是,我希望能够实时调整事件触发的时间段(根据用户输入)。
例如:
public class HelperTimer extends TimerTask
{
private Timer timer;
//Default of 15 second between updates
private int secondsToDelay = 15;
public void setPeriod(int seconds)
{
this.secondsToDelay = seconds;
long delay = 1000; // 1 second
long period = 1000*secondsToDelay; // seconds
if (timer != null)
{
timer.cancel();
}
System.out.println(timer);
timer = new Timer();
System.out.println(timer);
timer.schedule(this, delay, period);
}
public int getPeriod()
{
return this.secondsToDelay;
}
}
然后,我启动此类的新实例并调用其 set period 函数。但是,当我这样做时,我会收到一个非法状态异常。你可以看到 System.out.println(timer);在那里,因为我正在检查,是的,果然,它们是两个不同的计时器......那么,为什么当我尝试在全新的计时器实例上运行计划调用时,我会收到一个 IllegalStateException!?!?!?!
java.util.Timer@c55e36
java.util.Timer@9664a1
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Task already scheduled or cancelled
at java.util.Timer.sched(Unknown Source)
at java.util.Timer.schedule(Unknown Source)
at HelperTimer.setPeriod(HelperTimer.java:38)