您的位置:首页 > 其它

【开发过程问题汇总系列】【定时器】Timer运行的过程中把系统时间修改为以前的时间会停止运行的问题

2014-09-10 20:17 513 查看
最近项目中有一个负责的需求,需要使用定时器在tomcat启动后每隔1小时自动运行一次检查任务,问题的发现很偶然。

修改系统当前时间为未来的时间时,定时器不会出现问题,会一直运行,而把当前时间修改为过去的时间定时器会卡着不执行。

经过分析Timer定时器源码才知,时间往后调定时器一定不会执行的。

JDK1.6源码如下:

/**
* The main timer loop.  (See class comment.)
*/
private void mainLoop() {
while (true) {
try {
TimerTask task;
boolean taskFired;
synchronized(queue) {
// Wait for queue to become non-empty
while (queue.isEmpty() && newTasksMayBeScheduled)
queue.wait();
if (queue.isEmpty())
break; // Queue is empty and will forever remain; die

// Queue nonempty; look at first evt and do the right thing
long currentTime, executionTime;
task = queue.getMin();
synchronized(task.lock) {
if (task.state == TimerTask.CANCELLED) {
queue.removeMin();
continue;  // No action required, poll queue again
}
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
if (task.period == 0) { // Non-repeating, remove
queue.removeMin();
task.state = TimerTask.EXECUTED;
} else { // Repeating task, reschedule
queue.rescheduleMin(
task.period<0 ? currentTime   - task.period
: executionTime + task.period);
}
}
}
if (!taskFired) // Task hasn't yet fired; wait
queue.wait(executionTime - currentTime);
}
if (taskFired)  // Task fired; run it, holding no locks
task.run();
} catch(InterruptedException e) {
}
}
}


目前来看,只能采用起一个Thread在run方法中定义个死循环每隔一小时Thread.sleep(1L * 60 * 60 * 1000)来避免修改时间的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐