Timer较之Quartz结构相对简单,其原理更容易动,并且两个会有相似之处,可以在了解Timer之后在看Quartz可能会相对容易通透一点,在Quartz之前先了解一下Timer定时器,以下是JDK Api中的介绍:
初始化Timer时,会将其中的TaskQueue以及TimerThread也进行相应的初始化并且,会启动线程,使thread在一个wait状态。
/** * The timer task queue. This data structure is shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as appropriate, * and removing them from the queue when they're obsolete. */ private final TaskQueue queue = new TaskQueue(); /** * The timer thread. */ private final TimerThread thread = new TimerThread(queue); /** * Creates a new timer whose associated thread has the specified name. * The associated thread does <i>not</i> * {@linkplain Thread#setDaemon run as a daemon}. * * @param name the name of the associated thread * @throws NullPointerException if {@code name} is null * @since 1.5 */ //初始化时会将thead线程启动,使其在一个wait状态。 public Timer(String name) { thread.setName(name); thread.start(); } /** * Schedules the specified task for execution after the specified delay. * * @param task task to be scheduled. * @param delay delay in milliseconds before task is to be executed. * @throws IllegalArgumentException if <tt>delay</tt> is negative, or * <tt>delay + System.currentTimeMillis()</tt> is negative. * @throws IllegalStateException if task was already scheduled or * cancelled, timer was cancelled, or timer thread terminated. * @throws NullPointerException if {@code task} is null */ public void schedule(TimerTask task, long delay) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); sched(task, System.currentTimeMillis()+delay, 0); }
其中的核心schedule方法提供多个重载方法,提供给使用者,最终会调用sched方法。参数含义如下:task(具体执行动作),time(下一次执行时间),perid(每次执行时间间隔)。
/** * Schedule the specified timer task for execution at the specified * time with the specified period, in milliseconds. If period is * positive, the task is scheduled for repeated execution; if period is * zero, the task is scheduled for one-time execution. Time is specified * in Date.getTime() format. This method checks timer state, task state, * and initial execution time, but not period. * 计划指定的计时器任务,以便在指定的时间和指定的时间段执行,以毫秒为单位。 * 如果周期为正,则计划重复执行任务;如果周期为零,则计划一次性执行任务。 * 时间以日期指定。getTime()格式。此方法检查计时器状态、任务状态、和初始执行时间,但不检查周期。 * * @param task 具体执行动作。 * @param time 下次执行时间,时间戳。 * @param period 每次执行时间间隔,时间戳。 */ private void sched(TimerTask task, long time, long period) { if (time < 0) throw new IllegalArgumentException("Illegal execution time."); // Constrain value of period sufficiently to prevent numeric // overflow while still being effectively infinitely large. // 限制时间间隔的最大值 if (Math.abs(period) > (Long.MAX_VALUE >> 1)) period >>= 1; //同一个Timer并发调用sched时加重锁 synchronized(queue) { if (!thread.newTasksMayBeScheduled) throw new IllegalStateException("Timer already cancelled."); //不同Timer调用同一个task时,task加锁应用,task.lock为TimerTask类中的加锁标识。 synchronized(task.lock) { if (task.state != TimerTask.VIRGIN) throw new IllegalStateException( "Task already scheduled or cancelled"); task.nextExecutionTime = time; task.period = period; task.state = TimerTask.SCHEDULED; } //将task加入执行计划queue中。 queue.add(task); if (queue.getMin() == task) //getMin()获取执行计划中下一次执行,如果当前task为下次执行,则通知queue,不需要在wait queue.notify(); } }
TimerThread主要用于管理task重复的启用以及非重复task任务的删除,在上述Timer中,初始化时会启动以下线程,使thread到达运行状态,执行mainLoop方法,进而在该方法中在到等待状态。
/** * This flag is set to false by the reaper to inform us that there * are no more live references to our Timer object. Once this flag * is true and there are no more tasks in our queue, there is no * work left for us to do, so we terminate gracefully. Note that * this field is protected by queue's monitor! */ //是否继续执行,true标识继续,false标识结束,最终结束定时器,还需要清空执行计划queue。 boolean newTasksMayBeScheduled = true; /** * Our Timer's queue. We store this reference in preference to * a reference to the Timer so the reference graph remains acyclic. * Otherwise, the Timer would never be garbage-collected and this * thread would never go away. */ private TaskQueue queue; TimerThread(TaskQueue queue) { this.queue = queue; } public void run() { try { mainLoop(); } finally { // Someone killed this Thread, behave as if Timer cancelled //上述mainLoop执行结束 synchronized(queue) { newTasksMayBeScheduled = false; queue.clear(); // Eliminate obsolete references } } } /** * The main timer loop. (See class comment.) */ private void mainLoop() { while (true) { //??????无线执行for循环完成自动服务。 try { TimerTask task; boolean taskFired; //将一个执行计划queue,初始化多个TimerThread,并启动线程时,需要将queue加锁 synchronized(queue) { // Wait for queue to become non-empty while (queue.isEmpty() && newTasksMayBeScheduled) //执行计划中五可执行任务,并且为可执行状态时,则执行计划等待任务加入 queue.wait(); if (queue.isEmpty()) //如果如果queue为空,则退出不在进行,clear时 break; // Queue is empty and will forever remain; die // Queue nonempty; look at first evt and do the right thing //executionTime 下一次执行时间 long currentTime, executionTime; //获取下一次执行计划 task = queue.getMin(); //场景同一个task列入多个执行计划时, synchronized(task.lock) { if (task.state == TimerTask.CANCELLED) { //task状态为取消状态时,queue执行计划需要将task删除,并将queue按下一次执行时间进行排序。 queue.removeMin(); continue; // No action required, poll queue again } currentTime = System.currentTimeMillis(); executionTime = task.nextExecutionTime; if (taskFired = (executionTime<=currentTime)) { //taskFired(true) 下次执行时间小于等于当前时间时 if (task.period == 0) { // Non-repeating, remove //不存在时间间隔时,并且次执行时间小于等于当前时间时,标识非重复任务,则将之从执行计划中删除 queue.removeMin(); //并更新该task的执行状态 task.state = TimerTask.EXECUTED; } else { // Repeating task, reschedule //改task任务为重复执行任务,则更新下次执行时间,并且将queue执行计划按下次执行时间进行排序。 queue.rescheduleMin( task.period<0 ? currentTime - task.period : executionTime + task.period); } } } if (!taskFired) // Task hasn't yet fired; wait //taskFired(false) 下次执行时间大于当前时间时,则等待 queue.wait(executionTime - currentTime); } if (taskFired) // Task fired; run it, holding no locks //满足条件则执行task task.run(); } catch(InterruptedException e) { } } }
/** * Priority queue represented as a balanced binary heap: the two children * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is * ordered on the nextExecutionTime field: The TimerTask with the lowest * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For * each node n in the heap, and each descendant of n, d, * n.nextExecutionTime <= d.nextExecutionTime. */ //默认数组长度128 private TimerTask[] queue = new TimerTask[128]; /** * Adds a new task to the priority queue. */ //判断长度,并采用数组扩容 void add(TimerTask task) { // Grow backing store if necessary if (size + 1 == queue.length) queue = Arrays.copyOf(queue, 2*queue.length); queue[++size] = task; fixUp(size); } /** * Return the "head task" of the priority queue. (The head task is an * task with the lowest nextExecutionTime.) */ TimerTask getMin() { return queue[1]; } /** * Remove the head task from the priority queue. */ void removeMin() { queue[1] = queue[size]; queue[size--] = null; // Drop extra reference to prevent memory leak fixDown(1); } /** * Sets the nextExecutionTime associated with the head task to the * specified value, and adjusts priority queue accordingly. */ void rescheduleMin(long newTime) { queue[1].nextExecutionTime = newTime; fixDown(1); } /** * Establishes the heap invariant (described above) assuming the heap * satisfies the invariant except possibly for the leaf-node indexed by k * (which may have a nextExecutionTime less than its parent's). * * This method functions by "promoting" queue[k] up the hierarchy * (by swapping it with its parent) repeatedly until queue[k]'s * nextExecutionTime is greater than or equal to that of its parent. */ //将将执行计划queue[k]与queue[1]进行比较,执行计划靠前的则放入queue[1]中 private void fixUp(int k) { while (k > 1) { int j = k >> 1; if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } } /** * Establishes the heap invariant (described above) in the subtree * rooted at k, which is assumed to satisfy the heap invariant except * possibly for node k itself (which may have a nextExecutionTime greater * than its children's). * * This method functions by "demoting" queue[k] down the hierarchy * (by swapping it with its smaller child) repeatedly until queue[k]'s * nextExecutionTime is less than or equal to those of its children. */ private void fixDown(int k) { int j; while ((j = k << 1) <= size && j > 0) { if (j < size && queue[j].nextExecutionTime > queue[j+1].nextExecutionTime) j++; // j indexes smallest kid if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime) break; TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } }
简单示例
public class SimpleTimer { public static void main(String[] args) { Timer simpleTimer = new Timer("firstTime"); SimpleTask task = new SimpleTask(); //Object lock = new Object(); //1000毫秒后开始执行,每次间隔2000毫秒 simpleTimer.schedule(task,1000,2000); simpleTimer.schedule(task,1000,2000); } public static class SimpleTask extends TimerTask{ Integer index = 0; @Override public void run() { index = index + 1; System.out.println("************"+index); if(index == 10 ){ cancel(); } } } }
注:由于Timer采用单线程执行,未采用线程池,在遇到耗时较长的Job工作时,时间校准会出现误差