- 相關(guān)推薦
關(guān)于Timer和TimerTask
Timer 功能在指定的時(shí)間間隔內反復觸發(fā)指定窗口的定時(shí)器事件。下面yjbys小編為大家準備了關(guān)于Timer和TimerTask的文章,歡迎閱讀。
1.概覽
Timer是一種定時(shí)器工具,用來(lái)在一個(gè)后臺線(xiàn)程計劃執行指定任務(wù)。它可以計劃執行一個(gè)任務(wù)一次或反復多次。
TimerTask一個(gè)抽象類(lèi),它的子類(lèi)代表一個(gè)可以被Timer計劃的任務(wù)。
簡(jiǎn)單的一個(gè)例程:
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new Reminder(5);
System.out.println("Task scheduled.");
}
}
運行這個(gè)小例子,你會(huì )首先看到:
About to schedule task.
5秒鐘之后你會(huì )看到:
Time's up!
這個(gè)小例子可以說(shuō)明一些用Timer線(xiàn)程實(shí)現和計劃執行一個(gè)任務(wù)的基礎步驟:
實(shí)現自定義的TimerTask的子類(lèi),run方法包含要執行的任務(wù)代碼,在這個(gè)例子里,這個(gè)子類(lèi)就是RemindTask。
實(shí)例化Timer類(lèi),創(chuàng )建計時(shí)器后臺線(xiàn)程。
實(shí)例化任務(wù)對象 (new RemindTask()).
制定執行計劃。這里用schedule方法,第一個(gè)參數是TimerTask對象,第二個(gè)參數表示開(kāi)始執行前的延時(shí)時(shí)間(單位是milliseconds,這里定義了5000)。還有一種方法可以指定任務(wù)的執行時(shí)間,如下例,指定任務(wù)在11:01 p.m.執行:
//Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
Date time = calendar.getTime();
timer = new Timer();
timer.schedule(new RemindTask(), time);
2.終止Timer線(xiàn)程
默認情況下,只要一個(gè)程序的timer線(xiàn)程在運行,那么這個(gè)程序就會(huì )保持運行。當然,你可以通過(guò)以下四種方法終止一個(gè)timer線(xiàn)程:
調用timer的cancle方法。你可以從程序的任何地方調用此方法,甚至在一個(gè)timer task的run方法里。
讓timer線(xiàn)程成為一個(gè)daemon線(xiàn)程(可以在創(chuàng )建timer時(shí)使用new Timer(true)達到這個(gè)目地),這樣當程序只有daemon線(xiàn)程的時(shí)候,它就會(huì )自動(dòng)終止運行。
當timer相關(guān)的所有task執行完畢以后,刪除所有此timer對象的引用(置成null),這樣timer線(xiàn)程也會(huì )終止。
調用System.exit方法,使整個(gè)程序(所有線(xiàn)程)終止。
Reminder的例子使用了第一種方式。在這里不能使用第二種方式,因為這里需要程序保持運行直到timer的任務(wù)執行完成,如果設成daemon,那么當main線(xiàn)程結束的時(shí)候,程序只剩下timer這個(gè)daemon線(xiàn)程,于是程序不會(huì )等timer線(xiàn)程執行task就終止了。
有些時(shí)候,程序的終止與否并不只與timer線(xiàn)程有關(guān)。舉個(gè)例子,如果我們使用AWT來(lái)beep,那么AWT會(huì )自動(dòng)創(chuàng )建一個(gè)非daemon線(xiàn)程來(lái)保持程序的運行。
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
3.反復執行一個(gè)任務(wù)
先看一個(gè)例子:
public class AnnoyingBeep {
Toolkit toolkit;
Timer timer;
public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(),
0, //initial delay
1*1000); //subsequent rate
}
class RemindTask extends TimerTask {
int numWarningBeeps = 3;
public void run() {
if (numWarningBeeps > 0) {
toolkit.beep();
System.out.println("Beep!");
numWarningBeeps--;
} else {
toolkit.beep();
System.out.println("Time's up!");
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
}
...
}
執行,你會(huì )看到如下輸出:
Task scheduled.
Beep!
Beep! //one second after the first beep
Beep! //one second after the second beep
Time's up! //one second after the third beep
這里使用了三個(gè)參數的schedule方法用來(lái)指定task每隔一秒執行一次。如下所列為所有Timer類(lèi)用來(lái)制定計劃反復執行task的方法 :
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)
當計劃反復執行的任務(wù)時(shí),如果你注重任務(wù)執行的平滑度,那么請使用schedule方法,如果你在乎的是任務(wù)的執行頻度那么使用scheduleAtFixedRate方法。 例如,這里使用了schedule方法,這就意味著(zhù)所有beep之間的時(shí)間間隔至少為1秒,也就是說(shuō),如果有一個(gè)beap因為某種原因遲到了(未按計劃執行),那么余下的所有beep都要延時(shí)執行。如果我們想讓這個(gè)程序正好在3秒以后終止,無(wú)論哪一個(gè)beep因為什么原因被延時(shí),那么我們需要使用scheduleAtFixedRate方法,這樣當第一個(gè)beep遲到時(shí),那么后面的beep就會(huì )以最快的速度緊密執行(最大限度的壓縮間隔時(shí)間)。
4.進(jìn)一步分析schedule和scheduleAtFixedRate
(1)2個(gè)參數的schedule在制定任務(wù)計劃時(shí), 如果指定的計劃執行時(shí)間scheduledExecutionTime<=systemCurrentTime,則task會(huì )被立即執行。scheduledExecutionTime不會(huì )因為某一個(gè)task的過(guò)度執行而改變。
(2)3個(gè)參數的schedule在制定反復執行一個(gè)task的計劃時(shí),每一次執行這個(gè)task的計劃執行時(shí)間隨著(zhù)前一次的實(shí)際執行時(shí)間而變,也就是scheduledExecutionTime(第n+1次)=realExecutionTime(第n次)+periodTime。也就是說(shuō)如果第n次執行task時(shí),由于某種原因這次執行時(shí)間過(guò)長(cháng),執行完后的systemCurrentTime>=scheduledExecutionTime(第n+1次),則此時(shí)不做時(shí)隔等待,立即執行第n+1次task,而接下來(lái)的第n+2次task的scheduledExecutionTime(第n+2次)就隨著(zhù)變成了realExecutionTime(第n+1次)+periodTime。說(shuō)白了,這個(gè)方法更注重保持間隔時(shí)間的穩定。
(3)3個(gè)參數的scheduleAtFixedRate在制定反復執行一個(gè)task的計劃時(shí),每一次執行這個(gè)task的計劃執行時(shí)間在最初就被定下來(lái)了,也就是scheduledExecutionTime(第n次)=firstExecuteTime+n*periodTime;如果第n次執行task時(shí),由于某種原因這次執行時(shí)間過(guò)長(cháng),執行完后的systemCurrentTime>=scheduledExecutionTime(第n+1次),則此時(shí)不做period間隔等待,立即執行第n+1次task,而接下來(lái)的第n+2次的task的scheduledExecutionTime(第n+2次)依然還是firstExecuteTime+(n+2)*periodTime這在第一次執行task就定下來(lái)了。說(shuō)白了,這個(gè)方法更注重保持執行頻率的穩定。
5.一些注意的問(wèn)題
每一個(gè)Timer僅對應唯一一個(gè)線(xiàn)程。
Timer不保證任務(wù)執行的十分精確。
Timer類(lèi)的線(xiàn)程安全的。
【Timer和TimerTask】相關(guān)文章:
關(guān)于TimerTask與Timer類(lèi)的應用09-04
一個(gè)JavaScript的timer的代碼10-22
寒暄和交談06-28
PHP中MySQL、MySQLi和PDO的用法和區別07-01
考研英語(yǔ)(一)和英語(yǔ)(二)的題型和分值10-06
《將相和》文言文原文和譯文09-25
華為認證:HCIE和CCIE證書(shū)的未來(lái)和價(jià)值05-25
比較級和最高級的用法和構成08-19
紅茶和綠茶的區別04-27