Timer的主要方法有:ide
// 安排在指定的時間執行spa
void schedule(TimerTask task, Date time).net
// 安排在指定的時間開始以重複的延時執行線程
void schedule(TimerTask task, Date firstTime, long period)blog
// 安排在指定的延遲後執行get
void schedule(TimerTask task, long delay)it
// 安排在指定的延遲後開始以重複的延時執行io
void schedule(TimerTask task, long delay, long period)event
// 安排在指定的時間開始以重複的速率執行ast
void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
// 安排在指定的延遲後開始以重複的速率執行
void scheduleAtFixedRate(TimerTask task, long delay, long period)
注:重複的延時和重複的速率的區別在於,前者是在前一個任務的執行結束後間隔 period時間再開始下一次執行;而scheduleAtFixedRate則是會盡可能按照任務的初始時間來按照間隔period時間執行。若是一次任 務執行因爲某些緣由被延遲了,用schedule()調度的後續任務一樣也會被延遲,而用scheduleAtFixedRate()則會快速的開始兩次 或者屢次執行,是後續任務的執行時間可以遇上來。
ScheduledThreadPoolExecutor的主要方法:
// 在指定的延遲後執行
<V>ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)
// 在指定的延遲後執行
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
// 在指定的延遲後以固定速率執行(相似Timer.scheduleAtFixedRate())
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
// 在指定的延遲後以固定間隔執行(相似Timer.schedule())
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
比較:
·Timer對調度的支持是基於絕對時間的,所以任務對系統時間的改變是敏感的;而ScheduledThreadPoolExecutor支持相對時間。
·Timer使用單線程方式來執行全部的TimerTask,若是某個TimerTask很耗時則會影響到其餘TimerTask的執行;而ScheduledThreadPoolExecutor則能夠構造一個固定大小的線程池來執行任務。
·Timer不會捕獲由TimerTask拋出的未檢查異常,故當有異常拋出 時,Timer會終止,致使未執行完的TimerTask再也不執行,新的TimerTask也不能被調 度;ScheduledThreadPoolExecutor對這個問題進行了妥善的處理,不會影響其餘任務的執行。
結論:
Timer有這麼多的缺點,若是是使用JDK1.5以上的話,應該沒什麼理由要使用Timer來進行調度把:)
本文轉自:http://blog.csdn.net/masterseventeen/article/details/3443114