標籤: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