Java實現定時任務的三種方法

來源:互聯網
上載者:User

標籤:

普通thread

這是最常見的,建立一個thread,然後讓它在while迴圈裡一直運行著,通過sleep方法來達到定時任務的效果。這樣可以快速簡單的實現,代碼如下:

public class Task1 {public static void main(String[] args) {  // run in a second  final long timeInterval = 1000;  Runnable runnable = new Runnable() {  public void run() {    while (true) {      // ------- code for task to run      System.out.println("Hello !!");      // ------- ends here      try {       Thread.sleep(timeInterval);      } catch (InterruptedException e) {        e.printStackTrace();      }      }    }  };  Thread thread = new Thread(runnable);  thread.start();  }}

用Timer和TimerTask

上面的實現是非常快速簡便的,但它也缺少一些功能。
用Timer和TimerTask的話與上述方法相比有如下好處:

  • 當啟動和去取消任務時可以控制

  • 第一次執行任務時可以指定你想要的delay時間

在實現時,Timer類可以調度任務,TimerTask則是通過在run()方法裡實現具體任務。
Timer執行個體可以調度多任務,它是安全執行緒的。
當Timer的構造器被調用時,它建立了一個線程,這個線程可以用來調度任務:

import java.util.Timer;import java.util.TimerTask;public class Task2 {  public static void main(String[] args) {    TimerTask task = new TimerTask() {      @Override      public void run() {        // task to run goes here        System.out.println("Hello !!!");      }    };    Timer timer = new Timer();    long delay = 0;    long intevalPeriod = 1 * 1000;    // schedules the task to be run in an interval    timer.scheduleAtFixedRate(task, delay,                                intevalPeriod);  } // end of main}
ScheduledExecutorService

ScheduledExecutorService是從Java SE 5的java.util.concurrent裡,做為並發工具類被引進的,這是最理想的定時任務實現方式。
相比於上兩個方法,它有以下好處:

  •  相比於Timer的單線程,它是通過線程池的方式來執行任務的

  •  可以很靈活的去設定第一次執行任務delay時間

  •  提供了良好的約定,以便設定執行的時間間隔

 我們通過ScheduledExecutorService#scheduleAtFixedRate展示這個例子,通過代碼裡參數的控制,首次執行加了delay時間:

import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class Task3 {  public static void main(String[] args) {    Runnable runnable = new Runnable() {      public void run() {        // task to run goes here        System.out.println("Hello !!");      }    };    ScheduledExecutorService service = Executors                    .newSingleThreadScheduledExecutor();    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);  }}


Java實現定時任務的三種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.