清单 1. 使用 Timer 进行任务调度
package com.ibm.scheduler;import java.util.Timer;import java.util.TimerTask;public class TimerTest extends TimerTask {private String jobName="";public TimerTest(String jobName){ super(); this.jobName=jobName;}@Overridepublic void run() { // TODO Auto-generated method stub System.out.println("execute"+jobName);}public static void main(String[] args){ Timer timer=new Timer(); long delay1=1*1000; long period1=1000;
// 从现在开始 1 秒钟之后,每隔 1 秒钟执行一次 job1
timer.schedule(new TimerTest("job1"), delay1,period1);
long delay2=2*1000; long period2=2000;
// 从现在开始 2 秒钟之后,每隔 2 秒钟执行一次 job2
timer.schedule(new TimerTest("job2"), delay2,period2); } }
Output: execute job1 execute job1 execute job2 execute job1 execute job1 execute job2
使用Timer实现任务调度的核心类是Timer和TimerTask。其中Timer负责设定TimerTask的起始与间隔执行时间。使用者只需要创建一个TimerTask的继承类,实现自己的run方法,然后将其丢给Timer去执行即可。?
Timer的设计核心是一个TaskList和一个TaskThread。Timer将接收到任务丢到自己的TaskList中,TaskList按照Task的最初执行时间进行排序。TimerThread在创建Timer时会启动成为一个守护线程。这个线程会轮询所有任务,找到一个最近要执行的任务,然后休眠,当到达最近要执行任务的开始时间点,TimerThread被唤醒并执行该任务。之后TimerThread更新最近一个要执行的任务,继续休眠。
Timer的优点在于简单易用,但由于所有任务都是由通一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
?
ScheduleExecutor
鉴于Timer的上述缺陷,JAVA5推出了基于线程池设计的ScheduleExecutor。其设计思想是,每一个被调度的任务都会由线程池中的一个线程去执行,因此任务是并发执行的,相互之间不会受到干扰。需要注意的是,只有当任务的执行时间到来时。ScheduleExecutor才会真正启动一个线程,其余时间ScheduleExecutor都是轮询任务的状态。
清单 2. 使用 ScheduledExecutor 进行任务调度
package com.ibm.scheduler;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ScheduledExecutorTest implements Runnable {private String jobName="";public ScheduledExecutorTest(String jobName){ super(); this.jobName=jobName; }@Overridepublic void run() { // TODO Auto-generated method stub System.out.println("execute"+jobName);}public static void main(String[] args){ ScheduledExecutorService service=Executors.newScheduledThreadPool(10); long initialDelay1=1; long period1=1; // 从现在开始1秒钟之后,每隔1秒钟执行一次job1 service.scheduleAtFixedRate( new ScheduledExecutorTest("job1"),initialDelay1,period1,TimeUnit.SECONDS); long initialDelay2=2; long delay2=2; // 从现在开始2秒钟之后,每隔2秒钟执行一次job2 service.scheduleWithFixedDelay(new ScheduledExecutorTest("job2"),initialDelay2,delay2,TimeUnit.SECONDS);}}
Output: execute job1 execute job1 execute job2 execute job1 execute job1 execute job2
清单2展示了ScheduledExecutorService中两种最常见的调度方法ScheduleStFixedRate和ScheduleWithFixedDelay。ScheduleStFixedRate每次执行时间为上一次任务开始起向后推一个时间间隔,即每次执行时间为:initialDelay,initialDelay+period,initialDelay+2*period.....................................;
ScheduleWithFixedDelay每次执行时间为上一次任务结束起向后推一个时间间隔,即每次执行时间为:initialDelay,nitialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay...................;由此可见,ScheduleStFixedRate是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。
代码见附件
参考文献:
http://www.ibm.com/developerworks/cn/java/j-lo-taskschedule/index.html