36

How can I reschedule a timer. I have tried to cancel the timer/timertask and and schedule it again using a method. But its showing an exception error:

Exception errorjava.lang.IllegalStateException: TimerTask is scheduled already

Code I have used it :

private Timer timer = new Timer("alertTimer",true);
public void reScheduleTimer(int duration) {
    timer.cancel();
    timer.schedule(timerTask, 1000L, duration * 1000L);
}
Dijo David
  • 6,175
  • 11
  • 35
  • 46

4 Answers4

60

If you see the documentation on Timer.cancel() you'll see this:

"Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing."

You'll need to initialize a new Timer when you are rescheduling:

EDIT:

public void reScheduleTimer(int duration) {
  timer = new Timer("alertTimer",true);
  timerTask = new MyTimerTask();
  timer.schedule(timerTask, 1000L, duration * 1000L);
}

private class MyTimerTask extends TimerTask {
  @Override
  public void run() {
    // Do stuff
  }
}
Eric Nordvik
  • 14,656
  • 8
  • 42
  • 50
  • 6
    It's your timerTask that is the problem. Try recreating the timerTask when you reschedule the timer. – Eric Nordvik Mar 07 '11 at 08:59
  • Hi I have recreated the timerTask. There is no error but the sheduled task has been stopped. Can you please update the code in your answer so that I can refer it... – Dijo David Mar 07 '11 at 09:24
  • The timerTask MUST be a new TimerTask... otherwise it throws "TimerTask is scheduled already". Thanks for the example. – NoBugs Aug 03 '12 at 05:48
  • can it is takes more memory if it is running timer task in background after cancel() method and rechedule it – Benjamin Sep 28 '16 at 11:02
4

In fact, if you look in the cancel method javadoc, you can see the following thing :

Does not interfere with a currently executing task (if it exists).

That tells the timer "ok, no more tasks now, but you can finish the one you're doing". I think you'll also need to cancel the TimerTask.

Valentin Rocher
  • 11,667
  • 45
  • 59
1

@Eric Nordvik answer is running fine.

One thing we can do is to cancel previous timer events execution

public void reScheduleTimer(int duration) {

    // Cancel previous timer first
    timer.cancel();

    timer = new Timer("alertTimer",true);
    timerTask = new MyTimerTask();
    timer.schedule(timerTask, 1000L, duration * 1000L);
}
Kushal
  • 8,100
  • 9
  • 63
  • 82
-1

Actually you can use purge() so you don't have to initialize a new Timer.

public int purge ()

Added in API level 1 Removes all canceled tasks from the task queue. If there are no other references on the tasks, then after this call they are free to be garbage collected.

Returns the number of canceled tasks that were removed from the task queue.

Community
  • 1
  • 1
Rox Teddy
  • 101
  • 15