原創|其它|編輯:郝浩|2009-05-19 11:04:33.000|閱讀 757 次
概述:在應用開發中,經常需要一些周期性的操作,比如每5分鐘檢查一下新郵件等。對于這樣的操作最方便、高效的實現方式就是使用java.util.Timer工具類。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在應用開發中,經常需要一些周期性的操作,比如每5分鐘檢查一下新郵件等。對于這樣的操作最方便、高效的實現方式就是使用java.util.Timer工具類。比如下面的代碼每5分鐘檢查一遍是否有新郵件:
private java.util.Timer timer;
timer = new Timer(true);
timer.schedule(
new java.util.TimerTask() { public void run() { //server.checkNewMail(); 檢查新郵件 } }, 0, 5*60*1000);
使用這幾行代碼之后,Timer本身會每隔5分鐘調用一遍server.checkNewMail()方法,不需要自己啟動線程。Timer本身也是多線程同步的,多個線程可以共用一個Timer,不需要外部的同步代碼。
在《The Java Tutorial》中有更完整的例子:
public class AnnoyingBeep { T
oolkit 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)
}
}
}
...
}
這段程序,每隔3秒響鈴一聲,并打印出一行消息。循環3次。程序輸出如下:
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
Timer類也可以方便地用來作為延遲執行,比如下面的代碼延遲指定的時間(以秒為單位)執行某操作。類似電視的延遲關機功能。
...public class ReminderBeep {
... 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)
}
}
...
}
}
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:IT專家網論壇