一:簡單說明
ScheduleExecutorService介面中有四個重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在實現定時程式時比較方便。
下面是該介面的原型定義
java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor
介面scheduleAtFixedRate原型定義及參數說明
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit);
command:執行線程
initialDelay:初始化延時
period:兩次開始執行最小間隔時間
unit:計時單位
介面scheduleWithFixedDelay原型定義及參數說明
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);
command:執行線程
initialDelay:初始化延時
period:前一次執行結束到下一次執行開始的間隔時間(間隔執行延遲時間)
unit:計時單位
二:功能樣本
1.按指定頻率周期執行某個任務。
初始化延遲0ms開始執行,每隔100ms重新執行一次任務。
/** * 以固定周期頻率執行任務 */public static void executeFixedRate() {ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);executor.scheduleAtFixedRate(new EchoServer(),0,100,TimeUnit.MILLISECONDS);}
間隔指的是連續兩次任務開始執行的間隔。
2.按指定頻率間隔執行某個任務。
初始化時延時0ms開始執行,本次執行結束後延遲100ms開始下次執行。
/** * 以固定延遲時間進行執行 * 本次任務執行完成後,需要延遲設定的延遲時間,才會執行新的任務 */public static void executeFixedDelay() {ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);executor.scheduleWithFixedDelay(new EchoServer(),0,100,TimeUnit.MILLISECONDS);}
3.周期定時執行某個任務。
有時候我們希望一個任務被安排在淩晨3點(訪問較少時)周期性的執行一個比較耗費資源的任務,可以使用下面方法設定每天在固定時間執行一次任務。
/** * 每天晚上8點執行一次 * 每天定時安排任務進行執行 */public static void executeEightAtNightPerDay() {ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);long oneDay = 24 * 60 * 60 * 1000;long initDelay = getTimeMillis("20:00:00") - System.currentTimeMillis();initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;executor.scheduleAtFixedRate(new EchoServer(),initDelay,oneDay,TimeUnit.MILLISECONDS);}
/** * 擷取指定時間對應的毫秒數 * @param time "HH:mm:ss" * @return */private static long getTimeMillis(String time) {try {DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);return curDate.getTime();} catch (ParseException e) {e.printStackTrace();}return 0;}
4.輔助代碼
class EchoServer implements Runnable {@Overridepublic void run() {try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("This is a echo server. The current time is " +System.currentTimeMillis() + ".");}}
三:一些問題
上面寫的內容有不嚴謹的地方,比如對於scheduleAtFixedRate方法,當我們要執行的任務大於我們指定的執行間隔時會怎麼樣呢?
對於中文API中的注釋,我們可能會被忽悠,認為無論怎麼樣,它都會按照我們指定的間隔進行執行,其實當執行任務的時間大於我們指定的間隔時間時,它並不會在指定間隔時開闢一個新的線程並發執行這個任務。而是等待該線程執行完畢。
源碼注釋如下:
* Creates and executes a periodic action that becomes enabled first* after the given initial delay, and subsequently with the given* period; that is executions will commence after* <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then* <tt>initialDelay + 2 * period</tt>, and so on.* If any execution of the task* encounters an exception, subsequent executions are suppressed.* Otherwise, the task will only terminate via cancellation or* termination of the executor. If any execution of this task* takes longer than its period, then subsequent executions* may start late, but will not concurrently execute.
根據注釋中的內容,我們需要注意的時,我們需要捕獲最上層的異常,防止出現異常中止執行,導致周期性的任務不再執行。
四:除了我們自己實現定時任務之外,我們可以使用Spring幫我們完成這樣的事情。
Spring自動定時任務配置方法(我們要執行任務的類名為com.study.MyTimedTask)
<bean id="myTimedTask" class="com.study.MyTimedTask"/>
<bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><property name="targetObject" ref="myTimedTask"/><property name="targetMethod" value="execute"/><property name="concurrent" value="false"/></bean>
<bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"><property name="jobDetail" ref="doMyTimedTask"/><property name="cronExpression" value="0 0 2 * ?"/></bean>
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><ref local="myTimedTaskTrigger"/></list></property></bean>
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><bean class="org.springframework.scheduling.quartz.CronTriggerBean"><property name="jobDetail"/><bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><property name="targetObject"><bean class="com.study.MyTimedTask"/></property><property name="targetMethod" value="execute"/><property name="concurrent" value="false"/></bean></property><property name="cronExpression" value="0 0 2 * ?"/></bean></list></property></bean>