问题描述
如何重新安排计时器.我试图取消计时器/计时器任务并使用一种方法重新安排它.但它显示异常错误:
<前>异常错误java.lang.IllegalStateException: TimerTask 已经安排好了我用过的代码:
<前>private Timer timer = new Timer("alertTimer",true);公共无效reScheduleTimer(int持续时间){定时器.取消();timer.schedule(timerTask, 1000L, duration * 1000L);} 解决方案如果您查看有关 Timer.cancel() 的文档,您将看到:
取消计时器和所有计划任务.如果有当前正在运行的任务,它不会受到影响.不能在此计时器上安排更多任务.后续调用不执行任何操作."
重新安排时需要初始化一个新的计时器:
public void reScheduleTimer(int duration) {timer = new Timer("alertTimer",true);timerTask = new MyTimerTask();timer.schedule(timerTask, 1000L, duration * 1000L);}私有类 MyTimerTask 扩展了 TimerTask {@覆盖公共无效运行(){//做东西}}
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); }
解决方案
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
}
}
这篇关于在android中重新安排计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论