Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reschedule timer in android

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); } 
like image 974
Dijo David Avatar asked Mar 07 '11 08:03

Dijo David


2 Answers

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   } } 
like image 121
Eric Nordvik Avatar answered Oct 09 '22 11:10

Eric Nordvik


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.

like image 44
Valentin Rocher Avatar answered Oct 09 '22 13:10

Valentin Rocher