一、簡(jiǎn)介
在java中一個(gè)完整定時(shí)任務(wù)需要由Timer、TimerTask兩個(gè)類來配合完成运准。 API中是這樣定義他們的,Timer:一種工具缭受,線程用其安排以后在后臺(tái)線程中執(zhí)行的任務(wù)胁澳。可安排任務(wù)執(zhí)行一次米者,或者定期重復(fù)執(zhí)行韭畸。由TimerTask:Timer 安排為一次執(zhí)行或重復(fù)執(zhí)行的任務(wù)宇智。我們可以這樣理解Timer是一種定時(shí)器工具,用來在一個(gè)后臺(tái)線程計(jì)劃執(zhí)行指定任務(wù)胰丁,而TimerTask一個(gè)抽象類随橘,它的子類代表一個(gè)可以被Timer計(jì)劃的任務(wù)。
Timer類
在工具類Timer中锦庸,提供了四個(gè)構(gòu)造方法机蔗,每個(gè)構(gòu)造方法都啟動(dòng)了計(jì)時(shí)器線程,同時(shí)Timer類可以保證多個(gè)線程可以共享單個(gè)Timer對(duì)象而無需進(jìn)行外部同步酸员,所以Timer類是線程安全的蜒车。但是由于每一個(gè)Timer對(duì)象對(duì)應(yīng)的是單個(gè)后臺(tái)線程讳嘱,用于順序執(zhí)行所有的計(jì)時(shí)器任務(wù)幔嗦,一般情況下我們的線程任務(wù)執(zhí)行所消耗的時(shí)間應(yīng)該非常短,但是由于特殊情況導(dǎo)致某個(gè)定時(shí)器任務(wù)執(zhí)行的時(shí)間太長(zhǎng)沥潭,那么他就會(huì)“獨(dú)占”計(jì)時(shí)器的任務(wù)執(zhí)行線程邀泉,其后的所有線程都必須等待它執(zhí)行完,這就會(huì)延遲后續(xù)任務(wù)的執(zhí)行钝鸽,使這些任務(wù)堆積在一起,具體情況我們后面分析。
當(dāng)程序初始化完成Timer后垢揩,定時(shí)任務(wù)就會(huì)按照我們?cè)O(shè)定的時(shí)間去執(zhí)行闹获,Timer提供了schedule方法,該方法有多中重載方式來適應(yīng)不同的情況颜懊,如下:
schedule(TimerTask task, Date time):安排在指定的時(shí)間執(zhí)行指定的任務(wù)财岔。
schedule(TimerTask task, Date firstTime, long period) :安排指定的任務(wù)在指定的時(shí)間開始進(jìn)行重復(fù)的固定延遲執(zhí)行。
schedule(TimerTask task, long delay) :安排在指定延遲后執(zhí)行指定的任務(wù)河爹。
schedule(TimerTask task, long delay, long period) :安排指定的任務(wù)從指定的延遲后開始進(jìn)行重復(fù)的固定延遲執(zhí)行匠璧。
同時(shí)也重載了scheduleAtFixedRate方法,scheduleAtFixedRate方法與schedule相同咸这,只不過他們的側(cè)重點(diǎn)不同夷恍,區(qū)別后面分析。
scheduleAtFixedRate(TimerTask task, Date firstTime, long period):安排指定的任務(wù)在指定的時(shí)間開始進(jìn)行重復(fù)的固定速率執(zhí)行媳维。
scheduleAtFixedRate(TimerTask task, long delay, long period):安排指定的任務(wù)在指定的延遲后開始進(jìn)行重復(fù)的固定速率執(zhí)行酿雪。
TimerTask
TimerTask類是一個(gè)抽象類,由Timer 安排為一次執(zhí)行或重復(fù)執(zhí)行的任務(wù)侄刽。它有一個(gè)抽象方法run()方法指黎,該方法用于執(zhí)行相應(yīng)計(jì)時(shí)器任務(wù)要執(zhí)行的操作。因此每一個(gè)具體的任務(wù)類都必須繼承TimerTask唠梨,然后重寫run()方法袋励。
另外它還有兩個(gè)非抽象的方法:
boolean cancel():取消此計(jì)時(shí)器任務(wù)。
long scheduledExecutionTime():返回此任務(wù)最近實(shí)際執(zhí)行的安排執(zhí)行時(shí)間。
二茬故、實(shí)例
2.1盖灸、指定延遲時(shí)間執(zhí)行定時(shí)任務(wù)
public class TimerTest01 {
Timer timer;
public TimerTest01(int time){
timer = new Timer();
timer.schedule(new TimerTaskTest01(), time * 1000);
}
public static void main(String[] args) {
System.out.println(“timer begin…”);
new TimerTest01(3);
}
}
public class TimerTaskTest01 extends TimerTask{
public void run() {
System.out.println(“Time’s up!!!”);
}
}
運(yùn)行結(jié)果:
首先打印:timer begin…
3秒后打踊前拧:Time’s up!!!
2.2赁炎、在指定時(shí)間執(zhí)行定時(shí)任務(wù)
public class TimerTest02 {
Timer timer;
public TimerTest02(){
Date time = getTime();
System.out.println(“指定時(shí)間time=” + time);
timer = new Timer();
timer.schedule(new TimerTaskTest02(), time);
}
public Date getTime(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 11);
calendar.set(Calendar.MINUTE, 39);
calendar.set(Calendar.SECOND, 00);
Date time = calendar.getTime();
return time;
}
public static void main(String[] args) {
new TimerTest02();
}
}
public class TimerTaskTest02 extends TimerTask{
@Override
public void run() {
System.out.println(“指定時(shí)間執(zhí)行線程任務(wù)…”);
}
}
當(dāng)時(shí)間到達(dá)11:39:00時(shí)就會(huì)執(zhí)行該線程任務(wù),當(dāng)然大于該時(shí)間也會(huì)執(zhí)行!!執(zhí)行結(jié)果為:
指定時(shí)間time=Tue Jun 10 11:39:00 CST 2014
指定時(shí)間執(zhí)行線程任務(wù)…
2.3钾腺、在延遲指定時(shí)間后以指定的間隔時(shí)間循環(huán)執(zhí)行定時(shí)任務(wù)
public class TimerTest03 {
Timer timer;
public TimerTest03(){
timer = new Timer();
timer.schedule(new TimerTaskTest03(), 1000, 2000);
}
public static void main(String[] args) {
new TimerTest03();
}
}
public class TimerTaskTest03 extends TimerTask{
@Override
public void run() {
Date date = new Date(this.scheduledExecutionTime());
System.out.println(“本次執(zhí)行該線程的時(shí)間為:” + date);
}
}
運(yùn)行結(jié)果:
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:47 CST 2014
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:49 CST 2014
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:51 CST 2014
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:53 CST 2014
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:55 CST 2014
本次執(zhí)行該線程的時(shí)間為:Tue Jun 10 21:19:57 CST 2014
…
對(duì)于這個(gè)線程任務(wù),如果我們不將該任務(wù)停止,他會(huì)一直運(yùn)行下去徙垫。
對(duì)于上面三個(gè)實(shí)例,LZ只是簡(jiǎn)單的演示了一下放棒,同時(shí)也沒有講解scheduleAtFixedRate方法的例子姻报,其實(shí)該方法與schedule方法一樣!
2.4、分析schedule和scheduleAtFixedRate1间螟、schedule(TimerTask task, Date time)吴旋、schedule(TimerTask task, long delay)
對(duì)于這兩個(gè)方法而言,如果指定的計(jì)劃執(zhí)行時(shí)間scheduledExecutionTime<= systemCurrentTime厢破,則task會(huì)被立即執(zhí)行荣瑟。scheduledExecutionTime不會(huì)因?yàn)槟骋粋€(gè)task的過度執(zhí)行而改變。
2摩泪、schedule(TimerTask task, Date firstTime, long period)笆焰、schedule(TimerTask task, long delay, long period)
這兩個(gè)方法與上面兩個(gè)就有點(diǎn)兒不同的,前面提過Timer的計(jì)時(shí)器任務(wù)會(huì)因?yàn)榍耙粋€(gè)任務(wù)執(zhí)行時(shí)間較長(zhǎng)而延時(shí)见坑。在這兩個(gè)方法中嚷掠,每一次執(zhí)行的task的計(jì)劃時(shí)間會(huì)隨著前一個(gè)task的實(shí)際時(shí)間而發(fā)生改變,也就是scheduledExecutionTime(n+1)=realExecutionTime(n)+periodTime鳄梅。也就是說如果第n個(gè)task由于某種情況導(dǎo)致這次的執(zhí)行時(shí)間過程叠国,最后導(dǎo)致systemCurrentTime>= scheduledExecutionTime(n+1),這是第n+1個(gè)task并不會(huì)因?yàn)榈綍r(shí)了而執(zhí)行戴尸,他會(huì)等待第n個(gè)task執(zhí)行完之后再執(zhí)行粟焊,那么這樣勢(shì)必會(huì)導(dǎo)致n+2個(gè)的執(zhí)行實(shí)現(xiàn)scheduledExecutionTime放生改變即scheduledExecutionTime(n+2) = realExecutionTime(n+1)+periodTime。所以這兩個(gè)方法更加注重保存間隔時(shí)間的穩(wěn)定孙蒙。
3项棠、scheduleAtFixedRate(TimerTask task, Date firstTime, long period)、scheduleAtFixedRate(TimerTask task, long delay, long period)
在前面也提過scheduleAtFixedRate與schedule方法的側(cè)重點(diǎn)不同挎峦,schedule方法側(cè)重保存間隔時(shí)間的穩(wěn)定香追,而scheduleAtFixedRate方法更加側(cè)重于保持執(zhí)行頻率的穩(wěn)定。為什么這么說坦胶,原因如下透典。在schedule方法中會(huì)因?yàn)榍耙粋€(gè)任務(wù)的延遲而導(dǎo)致其后面的定時(shí)任務(wù)延時(shí)晴楔,而scheduleAtFixedRate方法則不會(huì),如果第n個(gè)task執(zhí)行時(shí)間過長(zhǎng)導(dǎo)致systemCurrentTime>= scheduledExecutionTime(n+1)峭咒,則不會(huì)做任何等待他會(huì)立即執(zhí)行第n+1個(gè)task税弃,所以scheduleAtFixedRate方法執(zhí)行時(shí)間的計(jì)算方法不同于schedule,而是scheduledExecutionTime(n)=firstExecuteTime +n*periodTime凑队,該計(jì)算方法永遠(yuǎn)保持不變则果。所以scheduleAtFixedRate更加側(cè)重于保持執(zhí)行頻率的穩(wěn)定。
三漩氨、Timer的缺陷
3.1西壮、Timer的缺陷Timer計(jì)時(shí)器可以定時(shí)(指定時(shí)間執(zhí)行任務(wù))、延遲(延遲5秒執(zhí)行任務(wù))叫惊、周期性地執(zhí)行任務(wù)(每隔個(gè)1秒執(zhí)行任務(wù))款青,但是,Timer存在一些缺陷赋访。首先Timer對(duì)調(diào)度的支持是基于絕對(duì)時(shí)間的可都,而不是相對(duì)時(shí)間,所以它對(duì)系統(tǒng)時(shí)間的改變非常敏感蚓耽。其次Timer線程是不會(huì)捕獲異常的,如果TimerTask拋出的了未檢查異常則會(huì)導(dǎo)致Timer線程終止旋炒,同時(shí)Timer也不會(huì)重新恢復(fù)線程的執(zhí)行步悠,他會(huì)錯(cuò)誤的認(rèn)為整個(gè)Timer線程都會(huì)取消。同時(shí)瘫镇,已經(jīng)被安排單尚未執(zhí)行的TimerTask也不會(huì)再執(zhí)行了鼎兽,新的任務(wù)也不能被調(diào)度。故如果TimerTask拋出未檢查的異常铣除,Timer將會(huì)產(chǎn)生無法預(yù)料的行為谚咬。
1、Timer管理時(shí)間延遲缺陷
前面Timer在執(zhí)行定時(shí)任務(wù)時(shí)只會(huì)創(chuàng)建一個(gè)線程任務(wù)尚粘,如果存在多個(gè)線程择卦,若其中某個(gè)線程因?yàn)槟撤N原因而導(dǎo)致線程任務(wù)執(zhí)行時(shí)間過長(zhǎng),超過了兩個(gè)任務(wù)的間隔時(shí)間郎嫁,會(huì)發(fā)生一些缺陷:
public class TimerTest04 {
private Timer timer;
public long start;
public TimerTest04(){
this.timer = new Timer();
start = System.currentTimeMillis();
}
public void timerOne(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println(“timerOne invoked ,the time:” + (System.currentTimeMillis() - start));
try {
Thread.sleep(4000); //線程休眠3000
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println(“timerOne invoked ,the time:” + (System.currentTimeMillis() - start));
}
}, 3000);
}
public static void main(String[] args) throws Exception {
TimerTest04 test = new TimerTest04();
test.timerOne();
test.timerTwo();
}
}
按照我們正常思路秉继,timerTwo應(yīng)該是在3s后執(zhí)行,其結(jié)果應(yīng)該是:
timerOne invoked ,the time:1001
timerOne invoked ,the time:3001
但是事與愿違泽铛,timerOne由于sleep(4000)尚辑,休眠了4S,同時(shí)Timer內(nèi)部是一個(gè)線程盔腔,導(dǎo)致timeOne所需的時(shí)間超過了間隔時(shí)間杠茬,結(jié)果:
timerOne invoked ,the time:1000
timerOne invoked ,the time:5000
2月褥、Timer拋出異常缺陷
如果TimerTask拋出RuntimeException,Timer會(huì)終止所有任務(wù)的運(yùn)行瓢喉。如下:
public class TimerTest04 {
private Timer timer;
public TimerTest04(){
this.timer = new Timer();
}
public void timerOne(){
timer.schedule(new TimerTask() {
public void run() {
throw new RuntimeException();
}
}, 1000);
}
public void timerTwo(){
timer.schedule(new TimerTask() {
public void run() {
System.out.println(“我會(huì)不會(huì)執(zhí)行呢??”);
}
}, 1000);
}
public static void main(String[] args) {
TimerTest04 test = new TimerTest04();
test.timerOne();
test.timerTwo();
}
}
運(yùn)行結(jié)果:timerOne拋出異常吓坚,導(dǎo)致timerTwo任務(wù)終止。
Exception in thread “Timer-0” java.lang.RuntimeException
at com.chenssy.timer.TimerTest04$1.run(TimerTest04.java:25)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
對(duì)于Timer的缺陷灯荧,我們可以考慮 ScheduledThreadPoolExecutor 來替代礁击。Timer是基于絕對(duì)時(shí)間的,對(duì)系統(tǒng)時(shí)間比較敏感逗载,而ScheduledThreadPoolExecutor 則是基于相對(duì)時(shí)間;Timer是內(nèi)部是單一線程哆窿,而ScheduledThreadPoolExecutor內(nèi)部是個(gè)線程池,所以可以支持多個(gè)任務(wù)并發(fā)執(zhí)行厉斟。
3.2挚躯、用ScheduledExecutorService替代Timer1、解決問題一:
public class ScheduledExecutorTest {
private ScheduledExecutorService scheduExec;
public long start;
ScheduledExecutorTest(){
this.scheduExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduExec.schedule(new Runnable() {
public void run() {
System.out.println(“timerOne,the time:” + (System.currentTimeMillis() - start));
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},1000,TimeUnit.MILLISECONDS);
}
public void timerTwo(){
scheduExec.schedule(new Runnable() {
public void run() {
System.out.println(“timerTwo,the time:” + (System.currentTimeMillis() - start));
}
},2000,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.timerOne();
test.timerTwo();
}
}
運(yùn)行結(jié)果:
timerOne,the time:1003
timerTwo,the time:2005
2擦秽、解決問題二
public class ScheduledExecutorTest {
private ScheduledExecutorService scheduExec;
public long start;
ScheduledExecutorTest(){
this.scheduExec = Executors.newScheduledThreadPool(2);
this.start = System.currentTimeMillis();
}
public void timerOne(){
scheduExec.schedule(new Runnable() {
public void run() {
throw new RuntimeException();
}
},1000,TimeUnit.MILLISECONDS);
}
public void timerTwo(){
scheduExec.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println(“timerTwo invoked …”);
}
},2000,500,TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
ScheduledExecutorTest test = new ScheduledExecutorTest();
test.timerOne();
test.timerTwo();
}
}
運(yùn)行結(jié)果:
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
timerTwo invoked …
…
最后給大家分享相關(guān)Java資料
java-數(shù)據(jù)類型
http://www.makeru.com.cn/live/1394_203.html?s=156461
集合
http://www.makeru.com.cn/live/1394_258.html?s=156461
構(gòu)造函數(shù)/繼承
http://www.makeru.com.cn/live/1394_243.html?s=156461