2011-03-07 61 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); 
}