在使用 Timer ,TimerTask类时,当使用Timer类方法mTimer.schedule(TimerTaskLock, 1000);,将同一个TimerTaskLock设置了两次是
如
- private Timer timer = new Timer("alertTimer",true);
- public void reScheduleTimer(int duration) {
- timer.cancel();
- timer.schedule(timerTask, 1000L, duration * 1000L);
- }
,会报TimerTask is scheduled already 异常。每一个Timer会单独开启一个线程。
解决思路:It's your timerTask that is the problem. Try recreating the timerTask when you reschedule the timer."
public void reScheduleTimer(int duration) {
timer.cancel();
timer.schedule(new TimerTask(), 1000L, duration * 1000L);//一可以使用同一Timer对象,但不能执行同一个TimerTask两次
}