最近项目中大量用到Timer 总结一下.
schedule安排指定的任务在指定的时间开始进行重复的固定延迟执行
scheduleAtFixedRate安排指定的任务从指定的延迟后开始进行重复的固定延迟执行
参考http://blog.youkuaiyun.com/gtuu0123/archive/2010/11/27/6040159.aspx 对schedule和scheduleAtFixedRate的分析.
但它仅仅分析了部分,查看JDK的源代码java.util.Timer分析以下几段:
public void schedule(TimerTask task, Date firstTime, long period) {
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, firstTime.getTime(), -period);
}
对比
public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
if (delay < 0)
throw new IllegalArgumentException("Negative delay.");
if (period <= 0)
throw new IllegalArgumentException("Non-positive period.");
sched(task, System.currentTimeMillis()+delay, period);
}
其调用void java.util.Timer .sched(TimerTask task, long time, long period) 方法,区别仅仅在于period传入方式.
再分析以下代码:
/**
* 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) {
}
}
}
以while(true)方式来调用task.run()方法.由此分析TimerTask中的run方法不存在同步的问题 ,如果执行时间超出设置时间,会直接再次执行run()而没有时间间隔!!!!