Reschedule timer in android

2019-01-17 06:01发布

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);
}

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-17 06:34

@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);
}
查看更多
Ridiculous、
3楼-- · 2019-01-17 06:37

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.

查看更多
Anthone
4楼-- · 2019-01-17 06:48

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
  }
}
查看更多
地球回转人心会变
5楼-- · 2019-01-17 06:56

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.

查看更多
登录 后发表回答