@Test public void scheduleTest(){ Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { System.out.println("task running"); } }; timer.schedule(task, LocalDate.parse("2016-04-01").toDate()); }當task執行完後其線程會一直處於等待狀態,只要把Timer改爲啓動時建立一個守護線程就好了。如:
Timer timer = new Timer(true);
如上:當timer執行task時建立的是一個守護線程。等主線程銷燬後其自動銷燬 java
注意:以守護線程執行task時會有必定的風險,好比主線程提前結束了,可是有可能task還在處理中。這樣task就可能被中斷了 ide
2.一個timer可能有多個task,schedule方法調用屢次等於添加多個task了。每一個task是以隊列的方式一個個被順序執行的(前提是task執行時間都在一個點上),因此越排後的task就會被延遲執行,由於要等到前面task的執行完嘛。因此這與給定的執行時間點就會不一致。 spa
3.schedule(TimerTask,Date,long) 該方法的做用是在指定的日期以後,按指定的間隔週期性地無限循環執行某一任務 線程
public static void scheduleTest(){ Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { System.out.println("task1 begin and time is "+LocalDateTime.now().toString()); Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, LocalDateTime.now().plusSeconds(3).toDate(),4000); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("task2 finished and time is "+LocalDateTime.now().toString()); } }, LocalDateTime.now().plusSeconds(2).toDate()) ; }如所示,timer添加了兩個task,一個是4秒執行一次(無限重複),一個是到點執行。
注意:若是task的處理時間大於4秒(延時),則下次的開始時間就是上次的結束時間。若是task的處理時間小於4秒(正常),那麼下次的開始時間=上次的開始+4秒 code