ScheduledExecutorService定時週期執行指定的任務

一:簡單說明

ScheduleExecutorService接口中有四個重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在實現定時程序時比較方便。

下面是該接口的原型定義

Java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor


接口scheduleAtFixedRate原型定義及參數說明

[java] view plain copy
  1. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,  
  2.             long initialDelay,  
  3.             long period,  
  4.             TimeUnit unit);  

command:執行線程
initialDelay:初始化延時
period:兩次開始執行最小間隔時間
unit:計時單位

接口scheduleWithFixedDelay原型定義及參數說明
[java] view plain copy
  1. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  
  2.                 long initialDelay,  
  3.                 long delay,  
  4.                 TimeUnit unit);  

command:執行線程
initialDelay:初始化延時
period:前一次執行結束到下一次執行開始的間隔時間(間隔執行延遲時間)
unit:計時單位

二:功能示例

1.按指定頻率週期執行某個任務。

初始化延遲0ms開始執行,每隔100ms重新執行一次任務。

[java] view plain copy
  1. /** 
  2.  * 以固定週期頻率執行任務 
  3.  */  
  4. public static void executeFixedRate() {  
  5.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  6.     executor.scheduleAtFixedRate(  
  7.             new EchoServer(),  
  8.             0,  
  9.             100,  
  10.             TimeUnit.MILLISECONDS);  
  11. }  
間隔指的是連續兩次任務開始執行的間隔。

2.按指定頻率間隔執行某個任務。

初始化時延時0ms開始執行,本次執行結束後延遲100ms開始下次執行。

[java] view plain copy
  1. /** 
  2.  * 以固定延遲時間進行執行 
  3.  * 本次任務執行完成後,需要延遲設定的延遲時間,纔會執行新的任務 
  4.  */  
  5. public static void executeFixedDelay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     executor.scheduleWithFixedDelay(  
  8.             new EchoServer(),  
  9.             0,  
  10.             100,  
  11.             TimeUnit.MILLISECONDS);  
  12. }  

3.週期定時執行某個任務。

有時候我們希望一個任務被安排在凌晨3點(訪問較少時)週期性的執行一個比較耗費資源的任務,可以使用下面方法設定每天在固定時間執行一次任務。

[java] view plain copy
  1. /** 
  2.  * 每天晚上8點執行一次 
  3.  * 每天定時安排任務進行執行 
  4.  */  
  5. public static void executeEightAtNightPerDay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     long oneDay = 24 * 60 * 60 * 1000;  
  8.     long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  
  9.     initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
  10.   
  11.     executor.scheduleAtFixedRate(  
  12.             new EchoServer(),  
  13.             initDelay,  
  14.             oneDay,  
  15.             TimeUnit.MILLISECONDS);  
  16. }  
[java] view plain copy
  1. /** 
  2.  * 獲取指定時間對應的毫秒數 
  3.  * @param time "HH:mm:ss" 
  4.  * @return 
  5.  */  
  6. private static long getTimeMillis(String time) {  
  7.     try {  
  8.         DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
  9.         DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
  10.         Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
  11.         return curDate.getTime();  
  12.     } catch (ParseException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15.     return 0;  
  16. }  

4.輔助代碼

[java] view plain copy
  1. class EchoServer implements Runnable {  
  2.     @Override  
  3.     public void run() {  
  4.         try {  
  5.             Thread.sleep(50);  
  6.         } catch (InterruptedException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.         System.out.println("This is a echo server. The current time is " +  
  10.                 System.currentTimeMillis() + ".");  
  11.     }  
  12. }  

三:一些問題

上面寫的內容有不嚴謹的地方,比如對於scheduleAtFixedRate方法,當我們要執行的任務大於我們指定的執行間隔時會怎麼樣呢?

對於中文API中的註釋,我們可能會被忽悠,認爲無論怎麼樣,它都會按照我們指定的間隔進行執行,其實當執行任務的時間大於我們指定的間隔時間時,它並不會在指定間隔時開闢一個新的線程併發執行這個任務。而是等待該線程執行完畢。

源碼註釋如下:

[java] view plain copy
  1. * Creates and executes a periodic action that becomes enabled first  
  2. * after the given initial delay, and subsequently with the given  
  3. * period; that is executions will commence after  
  4. * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then  
  5. * <tt>initialDelay + 2 * period</tt>, and so on.  
  6. * If any execution of the task  
  7. * encounters an exception, subsequent executions are suppressed.  
  8. * Otherwise, the task will only terminate via cancellation or  
  9. * termination of the executor.  If any execution of this task  
  10. * takes longer than its period, then subsequent executions  
  11. * may start late, but will not concurrently execute.  

根據註釋中的內容,我們需要注意的時,我們需要捕獲最上層的異常,防止出現異常中止執行,導致週期性的任務不再執行。

四:除了我們自己實現定時任務之外,我們可以使用spring幫我們完成這樣的事情。

Spring自動定時任務配置方法(我們要執行任務的類名爲com.study.MyTimedTask)

[html] view plain copy
  1. <bean id="myTimedTask" class="com.study.MyTimedTask"/>  

[html] view plain copy
  1. <bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  2.     <property name="targetObject" ref="myTimedTask"/>  
  3.     <property name="targetMethod" value="execute"/>  
  4.     <property name="concurrent" value="false"/>  
  5. </bean>  

[html] view plain copy
  1. <bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  2.     <property name="jobDetail" ref="doMyTimedTask"/>  
  3.     <property name="cronExpression" value="0 0 2 * ?"/>  
  4. </bean>  

[html] view plain copy
  1. <bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2.     <property name="triggers">  
  3.         <list>  
  4.             <ref local="myTimedTaskTrigger"/>  
  5.         </list>  
  6.     </property>  
  7. </bean>  

[html] view plain copy
  1. <bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  2.     <property name="triggers">  
  3.         <list>  
  4.             <bean class="org.springframework.scheduling.quartz.CronTriggerBean">  
  5.                 <property name="jobDetail"/>  
  6.                     <bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  7.                         <property name="targetObject">  
  8.                             <bean class="com.study.MyTimedTask"/>  
  9.                         </property>  
  10.                         <property name="targetMethod" value="execute"/>  
  11.                         <property name="concurrent" value="false"/>  
  12.                     </bean>  
  13.                 </property>  
  14.                 <property name="cronExpression" value="0 0 2 * ?"/>  
  15.             </bean>  
  16.         </list>  
  17.     </property>  
  18. </bean>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章