For some reason my java timer is not working in one of my programs. Whenever I compile my code, it gives me the following error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException:
Task already scheduled or cancelled
at java.util.Timer.sched(Timer.java:401)
at java.util.Timer.scheduleAtFixedRate(Timer.java:328)
Why is this? (Note: I am a novice at Java timers)
//Timer Prerequisites
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
public void run()
{
System.out.println("We have waited one second.");
}
};
//Check to see if user has enetered anything
while(!answered)
{
timer.scheduleAtFixedRate(task, 0, duration);
afk = true;
incorrect += 1;
answered = true;
}
A
Timer
can only be scheduled once, but the scheduling itself is at a fixed rate. Simply call thetimer.scheduleAtFixedRate
method once. If you need to start the same timer task later, you will need to construct a newjava.util.Timer
.