private ScheduledExecutorService scheduledExecutorService; scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); scheduledExecutorService.scheduleAtFixedRate(new Task(), 1, 4, TimeUnit.SECONDS);//4s一次 延遲1s task執行的一步任務 scheduledExecutorService.shutdown();//中止任務
new task 實現 runable接口;java
Timer存在一些缺陷:spa
1,Timer對調度的支持是基於絕對時間,而不是相對時間的,由此任務對系統時鐘的改變是敏感的;ScheduledThreadExecutor只支持相對時間。 線程
2,若是TimerTask拋出未檢查的異常,Timer將會產生沒法預料的行爲。Timer線程並不捕獲異常,因此 TimerTask拋出的未檢查的異常會終止timer線程。此時,已經被安排但還沒有執行的TimerTask永遠不會再執行了,新的任務也不能被調度了。 code