我试图用一个定时器来安排应用程序中的一个经常性事件。 不过,我希望能够在这实时事件触发(根据用户输入)调整期。
例如:
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;
}
}
然后我开始这个类的一个新实例,并调用其设定时间的功能。 然而,当我这样做,我得到一个非法状态异常。 你可以看到的System.out.println(定时器); 在那里,因为我正在检查,并没错果然,它们是两个不同的定时器...那么,为什么我会得到一个IllegalStateException当我尝试运行一个全新的Timer实例的时间表电话!?!?!?!
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)