定時任務Timer/TimerTask和ScheduledExecutorService

在咱們編程過程當中若是須要執行一些簡單的定時任務,無須作複雜的控制,咱們能夠考慮使用JDK中的Timer定時任務來實現。下面LZ就其原理、實例以及Timer缺陷三個方面來解析java Timer定時器。java

1、簡介
編程

在java中一個完整定時任務須要由Timer、TimerTask兩個類來配合完成。 API中是這樣定義他們的,Timer:一種工具,線程用其安排之後在後臺線程中執行的任務。可安排任務執行一次,或者按期重複執行。由TimerTask:Timer 安排爲一次執行或重複執行的任務。咱們能夠這樣理解Timer是一種定時器工具,用來在一個後臺線程計劃執行指定任務,而TimerTask一個抽象類,它的子類表明一個能夠被Timer計劃的任務。安全

Timer類

      在工具類Timer中,提供了四個構造方法,每一個構造方法都啓動了計時器線程,同時Timer類能夠保證多個線程能夠共享單個Timer對象而無需進行外部同步,因此Timer類是線程安全的。可是因爲每個Timer對象對應的是單個後臺線程,用於順序執行全部的計時器任務,通常狀況下咱們的線程任務執行所消耗的時間應該很是短,可是因爲特殊狀況致使某個定時器任務執行的時間太長,那麼他就會「獨佔」計時器的任務執行線程,其後的全部線程都必須等待它執行完,這就會延遲後續任務的執行,使這些任務堆積在一塊兒,具體狀況咱們後面分析。併發

      當程序初始化完成Timer後,定時任務就會按照咱們設定的時間去執行,Timer提供了schedule方法,該方法有多中重載方式來適應不一樣的狀況,以下:ide

      schedule(TimerTask task, Date time):安排在指定的時間執行指定的任務。工具

      schedule(TimerTask task, Date firstTime, long period) :安排指定的任務在指定的時間開始進行重複的固定延遲執行。oop

      schedule(TimerTask task, long delay) :安排在指定延遲後執行指定的任務。this

      schedule(TimerTask task, long delay, long period) :安排指定的任務從指定的延遲後開始進行重複的固定延遲執行。spa

      同時也重載了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、實例

 2.一、指定延遲時間執行定時任務

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.二、在指定時間執行定時任務

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  
指定時間執行線程任務...

 2.三、在延遲指定時間後以指定的間隔時間循環執行定時任務

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  
.................

對於這個線程任務,若是咱們不將該任務中止,他會一直運行下去。

      對於上面三個實例,LZ只是簡單的演示了一下,同時也沒有講解scheduleAtFixedRate方法的例子,其實該方法與schedule方法同樣!

2.四、分析schedule和scheduleAtFixedRate

      一、schedule(TimerTask task, Date time)、schedule(TimerTask task, long delay)

      對於這兩個方法而言,若是指定的計劃執行時間scheduledExecutionTime<= systemCurrentTime,則task會被當即執行。scheduledExecutionTime不會由於某一個task的過分執行而改變。

      二、schedule(TimerTask task, Date firstTime, long period)、schedule(TimerTask task, long delay, long period)

      這兩個方法與上面兩個就有點兒不一樣的,前面提過Timer的計時器任務會由於前一個任務執行時間較長而延時。在這兩個方法中,每一次執行的task的計劃時間會隨着前一個task的實際時間而發生改變,也就是scheduledExecutionTime(n+1)=realExecutionTime(n)+periodTime。也就是說若是第n個task因爲某種狀況致使此次的執行時間過程,最後致使systemCurrentTime>= scheduledExecutionTime(n+1),這是第n+1個task並不會由於到時了而執行,他會等待第n個task執行完以後再執行,那麼這樣勢必會致使n+2個的執行實現scheduledExecutionTime放生改變即scheduledExecutionTime(n+2) = realExecutionTime(n+1)+periodTime。因此這兩個方法更加註重保存間隔時間的穩定。

      三、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更加側重於保持執行頻率的穩定。

3、Timer的缺陷

3.一、Timer的缺陷

      Timer計時器能夠定時(指定時間執行任務)、延遲(延遲5秒執行任務)、週期性地執行任務(每隔個1秒執行任務),可是,Timer存在一些缺陷。首先Timer對調度的支持是基於絕對時間的,而不是相對時間,因此它對系統時間的改變很是敏感。其次Timer線程是不會捕獲異常的,若是TimerTask拋出的了未檢查異常則會致使Timer線程終止,同時Timer也不會從新恢復線程的執行,他會錯誤的認爲整個Timer線程都會取消。同時,已經被安排單還沒有執行的TimerTask也不會再執行了,新的任務也不能被調度。故若是TimerTask拋出未檢查的異常,Timer將會產生沒法預料的行爲。

      一、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);    //線程休眠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應該是在3s後執行,其結果應該是:

timerOne invoked ,the time:1001  
timerOne invoked ,the time:3001

可是事與願違,timerOne因爲sleep(4000),休眠了4S,同時Timer內部是一個線程,致使timeOne所需的時間超過了間隔時間,結果:

timerOne invoked ,the time:1000  
timerOne invoked ,the time:5000

二、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任務終止。

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)

對於Timer的缺陷,咱們能夠考慮 ScheduledThreadPoolExecutor 來替代。Timer是基於絕對時間的,對系統時間比較敏感,而ScheduledThreadPoolExecutor 則是基於相對時間;Timer是內部是單一線程,而ScheduledThreadPoolExecutor內部是個線程池,因此能夠支持多個任務併發執行。

3.二、用ScheduledExecutorService替代Timer

      一、解決問題一:

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

二、解決問題二

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 .....  
........................
相關文章
相關標籤/搜索