java定時任務之Timer和ScheduledExecutorService

來源:互聯網
上載者:User

標籤:exe   初始   override   task   大於   oid   invoke   service   cut   

java定時任務timer

1、執行多個任務的時候,必須第一個執行完後才會執行第二個。

2、timer是單線程執行,因此一個任務拋異常,其它任務也不能執行了。

 import java.util.Timer;   import java.util.TimerTask;      public class TimerTest   {       private static long start;          public static void main(String[] args) throws Exception       {              TimerTask task1 = new TimerTask()           {               @Override               public void run()               {                      System.out.println("task1 invoked ! "                           + (System.currentTimeMillis() - start));                   try                   {                       Thread.sleep(3000);                   } catch (InterruptedException e)                   {                       e.printStackTrace();                   }                  }           };           TimerTask task2 = new TimerTask()           {               @Override               public void run()               {                   System.out.println("task2 invoked ! "                           + (System.currentTimeMillis() - start));               }           };           Timer timer = new Timer();           start = System.currentTimeMillis();           timer.schedule(task1, 1000);           timer.schedule(task2, 3000);          }   }  

執行結果:

task1 invoked ! 1000

task2 invoked ! 4000

newScheduledThreadPool:

1、可以多個線程同時執行不同的任務。

2、因為是多個線程所有,任務拋出異常,不影響其它任務的執行。

  • scheduleAtFixedRate : 0s後開始執行任務,前一次任務的開始時間和下次任務的開始時間中間間隔是5s , 如果前一次任務執行時間大於5s ,那麼下次任務會在隊列種等待,直到前一次任務執行完後,再執行。
  • scheduleWithFixedDelay : 0s後開始執行任務,前一次任務的結束時間和後一次任務的開始時間中間間隔是5s。

    public class Scheduled {static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);static class Task implements Runnable {    public void run() {        try {            Thread.sleep(2000L);            System.out.println(Thread.currentThread().getName());        } catch (Exception e) {        }    }}/** * command:執行線程 * initialDelay:初始化延時 * period:兩次開始執行最小間隔時間 * delay:前一次執行結束到下一次執行開始的間隔時間(間隔執行延遲時間) * unit:計時單位 */public static void main(String[] args) {    scheduledExecutorService.scheduleAtFixedRate(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);    scheduledExecutorService.scheduleWithFixedDelay(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);}}

java定時任務之Timer和ScheduledExecutorService

聯繫我們

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