一、簡介
在java的jdk中提供了Timer、TimerTask兩個類來做定時任務。
Timer是一種定時器工具,用來在一個后台線程計划執行指定任務,而TimerTask一個抽象類,它的子類代表一個可以被Timer計划的任務。
---------------------
Timer類
在工具類Timer中,提供了四個構造方法,每個構造方法都啟動了計時器線程,同時Timer類可以保證多個線程可以共享單個Timer對象而無需進行外部同步,所以Timer類是線程安全的。但是由於每一個Timer對象對應的是單個后台線程,用於順序執行所有的計時器任務,一般情況下我們的線程任務執行所消耗的時間應該非常短,但是由於特殊情況導致某個定時器任務執行的時間太長,那么他就會“獨占”計時器的任務執行線程,其后的所有線程都必須等待它執行完,這就會延遲后續任務的執行,使這些任務堆積在一起,具體情況我們后面分析。
當程序初始化完成Timer后,定時任務就會按照我們設定的時間去執行,Timer提供了schedule方法,該方法有多種重載方式來適應不同的情況,如下:
schedule(TimerTask task, Date time):安排在指定的時間執行指定的任務。
schedule(TimerTask task, Date firstTime, long period) :安排指定的任務在指定的時間開始進行重復的固定延遲執行。
schedule(TimerTask task, long delay) :安排在指定延遲后執行指定的任務。
schedule(TimerTask task, long delay, long period) :安排指定的任務從指定的延遲后開始進行重復的固定延遲執行。
同時也重載了scheduleAtFixedRate方法,scheduleAtFixedRate方法與schedule相同,只不過他們的側重點不同,區別后面分析。
scheduleAtFixedRate(TimerTask task, Date firstTime, long period):安排指定的任務在指定的時間開始進行重復的固定速率執行。
scheduleAtFixedRate(TimerTask task, long delay, long period):安排指定的任務在指定的延遲后開始進行重復的固定速率執行。
TimerTask
TimerTask類是一個抽象類,由Timer 安排為一次執行或重復執行的任務。它有一個抽象方法run()方法,該方法用於執行相應計時器任務要執行的操作。因此每一個具體的任務類都必須繼承TimerTask,然后重寫run()方法。
另外它還有兩個非抽象的方法:
boolean cancel():取消此計時器任務。
long scheduledExecutionTime():返回此任務最近實際執行的安排執行時間。
二、實例
2.1、指定延遲時間執行定時任務
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!!!!"); } }
運行結果:
首先打印:timer begin....
3秒后打印:Time's up!!!!
2.2、在指定時間執行定時任務
public class TimerTest02 { Timer timer; public TimerTest02(){ Date time = getTime(); System.out.println("指定時間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("指定時間執行線程任務..."); } }
當時間到達11:39:00時就會執行該線程任務,當然大於該時間也會執行!!執行結果為:
指定時間time=Tue Jun 10 11:39:00 CST 2014
指定時間執行線程任務...
如果大於該時間不想要執行的解決辦法:
public class SandTimer { public void timerRun() { // 一天的毫秒數 long daySpan = 24 * 60 * 60 * 1000; // 規定的每天時間09:16:00運行 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 09:16:00"); // 首次運行時間 try { Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date())); // 如果今天的已經過了 首次運行時間就改為明天 if (System.currentTimeMillis() > startTime.getTime()){ startTime = new Date(startTime.getTime() + daySpan); } Timer t = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { System.out.print("定時器執行"); } }; // 以每24小時執行一次 t.schedule(task, startTime, daySpan); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new SandTimer().timerRun(); } --------------------- 作者:小貪1 來源:CSDN 原文:https://blog.csdn.net/x2570799116/article/details/78860448 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
2.3、在延遲指定時間后以指定的間隔時間循環執行定時任務
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("本次執行該線程的時間為:" + date); } }
運行結果:
本次執行該線程的時間為:Tue Jun 10 21:19:47 CST 2014 本次執行該線程的時間為:Tue Jun 10 21:19:49 CST 2014 本次執行該線程的時間為:Tue Jun 10 21:19:51 CST 2014 本次執行該線程的時間為:Tue Jun 10 21:19:53 CST 2014 本次執行該線程的時間為:Tue Jun 10 21:19:55 CST 2014 本次執行該線程的時間為:Tue Jun 10 21:19:57 CST 2014 ................
對於這個線程任務,如果我們不將該任務停止,他會一直運行下去。
2.4、分析schedule和scheduleAtFixedRate
1、schedule(TimerTask task, Date time)、schedule(TimerTask task, long delay)
對於這兩個方法而言,如果指定的計划執行時間scheduledExecutionTime<= systemCurrentTime,則task會被立即執行。scheduledExecutionTime不會因為某一個task的過度執行而改變。
2、schedule(TimerTask task, Date firstTime, long period)、schedule(TimerTask task, long delay, long period)
這兩個方法與上面兩個就有點兒不同的,前面提過Timer的計時器任務會因為前一個任務執行時間較長而延時。在這兩個方法中,每一次執行的task的計划時間會隨着前一個task的實際時間而發生改變,比如說本來是1,3,5這樣的時間間隔執行的,因為某種原因第一個任務執行了4秒鍾,那么就變成了1,7,9
3、scheduleAtFixedRate(TimerTask task, Date firstTime, long period)、scheduleAtFixedRate(TimerTask task, long delay, long period)
在前面也提過scheduleAtFixedRate與schedule方法的側重點不同,schedule方法側重保存間隔時間的穩定,而scheduleAtFixedRate方法更加側重於保持執行頻率的穩定。為什么這么說,原因如下。在schedule方法中會因為前一個任務的延遲而導致其后面的定時任務延時,而scheduleAtFixedRate方法則不會,如果第n個task執行時間過長導致systemCurrentTime>= scheduledExecutionTime(n+1),則不會做任何等待他會立即執行第n+1個task,所以scheduleAtFixedRate方法執行時間的計算方法不同於schedule,而是scheduledExecutionTime(n)=firstExecuteTime +n*periodTime,該計算方法永遠保持不變。所以scheduleAtFixedRate更加側重於保持執行頻率的穩定。
就是說,本來它是計划1,3,5這樣的間隔執行的,那么一定會是1,3,5這樣的時間點執行,不管前面的任務執行了多少時間。
三、Timer的缺陷
3.1、Timer的缺陷
1.Timer對調度的支持是基於絕對時間的,而不是相對時間,所以它對系統時間的改變非常敏感。
2.Timer線程是不會捕獲異常的,如果TimerTask拋出的了未檢查異常則會導致Timer線程終止,同時Timer也不會重新恢復線程的執行,他會錯誤的認為整個Timer線程都會取消。 同時,已經被安排但尚未執行的TimerTask也不會再執行了,新的任務也不能被調度。故如果TimerTask拋出未檢查的異常,Timer將會產生無法預料的行為。
1、Timer管理時間延遲缺陷
前面Timer在執行定時任務時只會創建一個線程任務,如果存在多個線程,若其中某個線程因為某種原因而導致線程任務執行時間過長,超過了兩個任務的間隔時間,會發生一些缺陷:
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); //線程休眠4000 } catch (InterruptedException e) { e.printStackTrace(); } } }, 1000); } public void timerTwo(){ timer.schedule(new TimerTask() { public void run() { System.out.println("timerTwo invoked ,the time:" + (System.currentTimeMillis() - start)); } }, 3000); } public static void main(String[] args) throws Exception { TimerTest04 test = new TimerTest04(); test.timerOne(); test.timerTwo(); } }
按照我們正常思路,timerTwo應該是在3s后執行,其結果應該是:
timerOne invoked ,the time:1001
timerOne invoked ,the time:3001
但是事與願違,timerOne由於sleep(4000),休眠了4S,同時Timer內部是一個線程,導致timeOne所需的時間超過了間隔時間,結果:
timerOne invoked ,the time:1000
timerTwo invoked ,the time:5001
2、Timer拋出異常缺陷
如果TimerTask拋出RuntimeException,Timer會終止所有任務的運行。如下:
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("我會不會執行呢??"); } }, 1000); } public static void main(String[] args) { TimerTest04 test = new TimerTest04(); test.timerOne(); test.timerTwo(); } }
運行結果:timerOne拋出異常,導致timerTwo任務終止。
3.2、用ScheduledExecutorService替代Timer
1、解決問題一:
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(); } }
運行結果:
timerOne,the time:1003
timerTwo,the time:2005 這2個時間每次執行都會有些偏差
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(); } }
運行結果:
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
timerTwo invoked .....
........................
原文出自:http://cmsblogs.com/?p=1175。尊重作者的成果,轉載請注明出處! 此文我做了一點點的修改