使用java內建的定時任務ScheduledThreadPoolExecutor

來源:互聯網
上載者:User

標籤:命令   sim   meta   順序   fifo   沒有   結束   oid   .sh   

ScheduledThreadPoolExecutor是ThreadPoolExecutor的子類;

JDK api裡是這麼說的:

 

ThreadPoolExecutor,它可另行安排在給定的延遲後運行命令,或者定期執行命令。需要多個輔助線程時,或者要求 ThreadPoolExecutor 具有額外的靈活性或功能時,此類要優於 Timer。

一旦啟用已延遲的任務就執行它,但是有關何時啟用,啟用後何時執行則沒有任何即時保證。按照提交的先進先出 (FIFO) 順序來啟用那些被安排在同一執行時間的任務。

---------------

平時我們在執行一個定時任務時,會採用Time,和TimeTask來組合處理;

但是Timer和TimerTask存在一些缺陷:

1:Timer只建立了一個線程。當你的任務執行的時間超過設定的延時時間將會產生一些問題。

2:Timer建立的線程沒有處理異常,因此一旦拋出非受檢異常,該線程會立即終止。

JDK 5.0以後推薦使用ScheduledThreadPoolExecutor。該類屬於Executor Framework,它除了能處理異常外,還可以建立多個線程解決上面的問題

 

 

 1 package timer; 2  3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 import java.util.concurrent.ScheduledThreadPoolExecutor; 6 import java.util.concurrent.TimeUnit; 7  8 public class Test 9 {10     static ScheduledThreadPoolExecutor stp = null;11     static int index;12     13     private static String getTimes() {  14         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");  15         Date date = new Date();  16         date.setTime(System.currentTimeMillis());  17         return format.format(date);  18     } 19     20     21     private static class MyTask implements Runnable {  22         23         @Override  24         public void run() {  25             index++;  26             System.out.println("2= " + getTimes()+" "  +index);  27 //            if(index >=10){  28 //                stp.shutdown();  29 //                if(stp.isShutdown()){  30 //                    System.out.println("停止了????");31 //                } 32 //            }33         }34     }35     public static void main(String[] args)36     {37         stp = new ScheduledThreadPoolExecutor(5);38         MyTask mytask = new MyTask();39         //mytask為線程,2是首次執行的延遲時間,最後一個參數為時間單位40 //        stp.schedule(mytask, 2, TimeUnit.SECONDS);41         // 首次執行延遲2秒,之後的執行循環是1秒42 //        stp.scheduleAtFixedRate(mytask, 2, 1,TimeUnit.SECONDS );43         //首次執行延遲2秒,之後從上一次任務結束到下一次任務開始時1秒44         stp.scheduleWithFixedDelay(mytask, 2, 1, TimeUnit.SECONDS);45         46     }47 48 }

 

使用java內建的定時任務ScheduledThreadPoolExecutor

聯繫我們

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