幾種任務調度的 Java 實現方法與比較(定時任務)

來源:互聯網
上載者:User

綜觀目前的 Web 應用程式,多數應用都具備任務調度的功能。本文由淺入深介紹了幾種任務調度的 Java 實現方法,包括 Timer,Scheduler, Quartz 以及 JCron Tab,並對其優缺點進行比較,目的在於給需要開發工作單位調度的程式員提供有價值的參考。

前言

任務調度是指基於給定時間點,給定時間間隔或者給定執行次數自動執行任務。本文由淺入深介紹四種任務調度的 Java 實現: Timer ScheduledExecutor 開源工具包 Quartz 開源工具包 JCronTab

此外,為結合實現複雜的任務調度,本文還將介紹 Calendar 的一些使用方法。

Timer

相信大家都已經非常熟悉 java.util.Timer 了,它是最簡單的一種實現任務調度的方法,下面給出一個具體的例子: view source print ?

01 package com.ibm.scheduler; 
02  import java.util.Timer; 
03  import java.util.TimerTask; 
04   
05  public class TimerTest extends TimerTask { 
06   
07  private String jobName = ""; 
08   
09  public TimerTest(String jobName) { 
10  super(); 
11  this.jobName = jobName; 
12  } 
13   
14  @Override 
15  public void run() { 
16  System.out.println("execute " + jobName); 
17  } 
18   
19  public static void main(String[] args) { 
20  Timer timer = new Timer(); 
21  long delay1 = 1 * 1000; 
22  long period1 = 1000; 
23  // 從現在開始 1 秒鐘之後,每隔 1 秒鐘執行一次 job1 
24  timer.schedule(new TimerTest("job1"), delay1, period1); 
25  long delay2 = 2 * 1000; 
26  long period2 = 2000; 
27  // 從現在開始 2 秒鐘之後,每隔 2 秒鐘執行一次 job2 
28  timer.schedule(new TimerTest("job2"), delay2, period2); 
29  } 
30  } 
31 /**
32  輸出結果: 
33  execute job1 
34  execute job1 
35  execute job2 
36  execute job1 
37  execute job1 
38  execute job2 
39 */

使用 Timer 實現任務調度的核心類是 Timer 和 TimerTask。其中 Timer 負責設定 TimerTask 的起始與間隔執行時間。使用者只需要建立一個 TimerTask 的繼承類,實現自己的 run 方法,然後將其丟給 Timer 去執行即可。

Timer 的設計核心是一個 TaskList 和一個 TaskThread。Timer 將接收到的任務丟到自己的 TaskList 中,TaskList 按照 Task 的最初執行時間進行排序。TimerThread 在建立 Timer 時會啟動成為一個守護線程。這個線程會輪詢所有任務,找到一個最近要執行的任務,然後休眠,當到達最近要執行任務的開始時間點,TimerThread 被喚醒並執行該任務。之後 TimerThread 更新最近一個要執行的任務,繼續休眠。

Timer 的優點在於簡單易用,但由於所有任務都是由同一個線程來調度,因此所有任務都是串列執行的,同一時間只能有一個任務在執行,前一個任務的延遲或異常都將會影響到之後的任務。

ScheduledExecutor

鑒於 Timer 的上述缺陷,Java 5 推出了基於線程池設計的 ScheduledExecutor。其設計思想是,每一個被調度的任務都會由線程池中一個線程去執行,因此任務是並發執行的,相互之間不會受到幹擾。需 要注意的是,只有當任務的執行時間到來時,ScheduedExecutor 才會真正啟動一個線程,其餘時間 ScheduledExecutor 都是在輪詢任務的狀態。 view source print ?

01 package com.ibm.scheduler;
02 import java.util.concurrent.Executors;
03 import java.util.concurrent.ScheduledExecutorService;
04 import java.util.concurrent.TimeUnit;
05   
06 public class ScheduledExecutorTest implements Runnable {
07     private String jobName = "";
08   
09     public ScheduledExecutorTest(String jobName) {
10         super();
11         this.jobName = jobName;
12     }
13   
14     @Override
15     public void run() {
16         System.out.println("execute " + jobName);
17     }
18   
19     public static void main(String[] args) {
20         ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
21   
22         long initialDelay1 = 1;
23         long period1 = 1;
24         // 從現在開始1秒鐘之後,每隔1秒鐘執行一次job1
25         service.scheduleAtFixedRate(
26                 new ScheduledExecutorTest("job1"), initialDelay1,
27                 period1, TimeUnit.SECONDS);
28   
29         long initialDelay2 = 1;
30         long delay2 = 1;
31         // 從現在開始2秒鐘之後,每隔2秒鐘執行一次job2
32         service.scheduleWithFixedDelay(
33                 new ScheduledExecutorTest("job2"), initialDelay2,
34                 delay2, TimeUnit.SECONDS);
35     }
36 }
37 /**
38 輸出結果:
39 execute job1
40 execute job1
41 execute job2
42 execute job1
43 execute job1
44 execute job2
45 */

上面代碼展示了 ScheduledExecutorService 中兩種最常用的調度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次執行時間為上一次任務開始起向後推一個時間間隔,即每次執行時間為 :initialDelay, initialDelay+period, initialDelay+2*period, …;ScheduleWithFixedDelay 每次執行時間為上一次任務結束起向後推一個時間間隔,即每次執行時間為:initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay。由此可見,ScheduleAtFixedRate 是基於固定時間間隔進行任務調度,ScheduleWithFixedDelay 取決於每次任務執行的時間長短,是基於不固定時間間隔進行任務調度。  

用 ScheduledExecutor 和 Calendar 實現複雜任務調度

Timer 和 ScheduledExecutor 都僅能提供基於開始時間與重複間隔的任務調度,不能勝任更加複雜的調度需求。比如,設定每星期二的 16:38:10 執行任務。該功能使用 Timer 和 ScheduledExecutor 都不能直接實現,但我們可以藉助 Calendar 間接實現該功能。 view source print

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.