2011-03-07 71 views
32

我怎麼可以重新計時。我試圖取消定時器/時間任務,並使用一種方法重新安排它。但其顯示的異常錯誤:重新安排計時器在Android的

 
Exception errorjava.lang.IllegalStateException: TimerTask is scheduled already 

代碼我已經用它:

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

這將是更容易幫助,如果你張貼在您取消計時器的代碼。 – 2011-03-07 08:22:51

+0

請你給我們您一直使用做到這一點的代碼?以這種方式幫助你會容易得多 – 2011-03-07 08:23:23

+0

我已經添加了我的代碼。我不確定它的正確與否。我也嘗試通過取消timeTask。 – 2011-03-07 08:29:50

回答

55

如果您看到Timer.cancel(文檔),你會看到:。

「取消定時器和所有預定任務,如果有一個當前正在運行的任務,它不會受到影響沒有更多的任務可能被安排在這個定時器上,隨後的調用什麼都不做。「

你需要初始化一個新的計時器,當你重新安排:

編輯:

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 
    } 
} 
+4

我都試過,但仍是錯誤表演! :( – 2011-03-07 08:48:57

+5

這是你的TimerTask這就是問題所在。請嘗試重新創建TimerTask的,當你重新安排計時器。 – 2011-03-07 08:59:06

+0

您好我已經重新創建TimerTask的,沒有錯誤,但sheduled任務已停止。能否請你在你的答案更新代碼所以我可以參考它... – 2011-03-07 09:24:03

4

事實上,如果你在cancel method javadoc看,你可以看到如下的事情:

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

這告訴計時器「好了,沒有更多的任務現在,但你可以完成你正在做的一個」。我想你還需要cancel the TimerTask

+0

感謝瓦倫丁羅徹... – 2011-03-07 11:21:21

-1

其實你可以使用purge()所以你不必初始化一個新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.

+0

它沒有工作對我來說這是需要更多的內存....我試了...你能給出的API調用序列這個? – Kushal 2015-12-08 11:38:40

0

@Eric Nordvik答案運行良好。

有一件事我們可以做的是取消先前的計時器事件執行

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