【摘抄】關於Java schedule job Timer的schedule方法詳解

Timer timer = new Timer(true);
timer.schedule(TimerTask, delay, interval);

創建timer時使用new Timer(true)可以使timer線程成爲一個daemon線程,這樣當程序只有daemon線程的時候,它就會自動終止運行。  

Timer的schedule函數有四種:

schedule(TimerTask task, long delay, long period)  
schedule(TimerTask task, Date time, long period)  
scheduleAtFixedRate(TimerTask task, long delay, long period)  
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)  

(1) 2個參數的schedule在制定任務計劃時, 如果指定的計劃執行時間scheduledExecutionTime<= systemCurrentTime,則task會被立即執行。scheduledExecutionTime不會因爲某一個task的過度執行而改變。 
(2) 3個參數的schedule在制定反覆執行一個task的計劃時,每一次執行這個task的計劃執行時間隨着前一次的實際執行時間而變,也就是 scheduledExecutionTime(第n+1次)=realExecutionTime(第n次)+periodTime。也就是說如果第n 次執行task時,由於某種原因這次執行時間過長,執行完後的systemCurrentTime>= scheduledExecutionTime(第n+1次),則此時不做時隔等待,立即執行第n+1次task,而接下來的第n+2次task的 scheduledExecutionTime(第n+2次)就隨着變成了realExecutionTime(第n+1次)+periodTime。說 白了,這個方法更注重保持間隔時間的穩定。 
(3)3個參數的scheduleAtFixedRate在制定反覆執行一個task的計劃時,每一次 執行這個task的計劃執行時間在最初就被定下來了,也就是scheduledExecutionTime(第n次)=firstExecuteTime +n*periodTime;如果第n次執行task時,由於某種原因這次執行時間過長,執行完後的systemCurrentTime>= scheduledExecutionTime(第n+1次),則此時不做period間隔等待,立即執行第n+1次task,而接下來的第n+2次的 task的scheduledExecutionTime(第n+2次)依然還是firstExecuteTime+(n+2)*periodTime這 在第一次執行task就定下來了。說白了,這個方法更注重保持執行頻率的穩定。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章