ScheduleExecutorService定時調用

一:簡單說明java

ScheduleExecutorService接口中有四個重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在實現定時程序時比較方便。併發

下面是該接口的原型定義ide

Java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executorthis

接口scheduleAtFixedRate原型定義及參數說明spa

ScheduledFuture<?> java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate(.net

        Runnable command,線程

        long initialDelay,orm

        long period,server

        TimeUnit unit)接口

command:執行線程
initialDelay:初始化延時
period:兩次開始執行最小間隔時間
unit:計時單位

接口scheduleWithFixedDelay原型定義及參數說明

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  

                long initialDelay,  

                long delay,  

                TimeUnit unit);  

command:執行線程
initialDelay:初始化延時
period:前一次執行結束到下一次執行開始的間隔時間(間隔執行延遲時間)
unit:計時單位

二:功能示例

1.按指定頻率週期執行某個任務。

初始化延遲0ms開始執行,每隔100ms從新執行一次任務。

/** 

 * 以固定週期頻率執行任務 

 */  

public static void executeFixedRate() {  

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  

    executor.scheduleAtFixedRate(  

            new EchoServer(),  

            0,  

            100,  

            TimeUnit.MILLISECONDS);  

}  

間隔指的是連續兩次任務開始執行的間隔。

 

2.按指定頻率間隔執行某個任務。

初始化時延時0ms開始執行,本次執行結束後延遲100ms開始下次執行。

/** 

 * 以固定延遲時間進行執行 

 * 本次任務執行完成後,須要延遲設定的延遲時間,纔會執行新的任務 

 */  

public static void executeFixedDelay() {  

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  

    executor.scheduleWithFixedDelay(  

            new EchoServer(),  

            0,  

            100,  

            TimeUnit.MILLISECONDS);  

}  

3.週期定時執行某個任務。

有時候咱們但願一個任務被安排在凌晨3點(訪問較少時)週期性的執行一個比較耗費資源的任務,能夠使用下面方法設定天天在固定時間執行一次任務。

/** 

 * 天天晚上8點執行一次 

 * 天天定時安排任務進行執行 

 */  

public static void executeEightAtNightPerDay() {  

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  

    long oneDay = 24 * 60 * 60 * 1000;  

    long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  

    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  

  

    executor.scheduleAtFixedRate(  

            new EchoServer(),  

            initDelay,  

            oneDay,  

            TimeUnit.MILLISECONDS);  

/** 

 * 獲取指定時間對應的毫秒數 

 * @param time "HH:mm:ss" 

 * @return 

 */  

private static long getTimeMillis(String time) {  

    try {  

        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  

        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  

        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  

        return curDate.getTime();  

    } catch (ParseException e) {  

        e.printStackTrace();  

    }  

    return 0;  

}  

4.輔助代碼

class EchoServer implements Runnable {  

    @Override  

    public void run() {  

        try {  

            Thread.sleep(50);  

        } catch (InterruptedException e) {  

            e.printStackTrace();  

        }  

        System.out.println("This is a echo server. The current time is " +  

                System.currentTimeMillis() + ".");  

    }  

}  

三:一些問題

上面寫的內容有不嚴謹的地方,好比對於scheduleAtFixedRate方法,當咱們要執行的任務大於咱們指定的執行間隔時會怎麼樣呢?

對於中文API中的註釋,咱們可能會被忽悠,認爲不管怎麼樣,它都會按照咱們指定的間隔進行執行,其實當執行任務的時間大於咱們指定的間隔時間時,它並不會在指定間隔時開闢一個新的線程併發執行這個任務。而是等待該線程執行完畢。

源碼註釋以下:

* Creates and executes a periodic action that becomes enabled first  

* after the given initial delay, and subsequently with the given  

* period; that is executions will commence after  

* <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then  

* <tt>initialDelay + 2 * period</tt>, and so on.  

* If any execution of the task  

* encounters an exception, subsequent executions are suppressed.  

* Otherwise, the task will only terminate via cancellation or  

* termination of the executor.  If any execution of this task  

* takes longer than its period, then subsequent executions  

* may start late, but will not concurrently execute.  

根據註釋中的內容,咱們須要注意的時,咱們須要捕獲最上層的異常,防止出現異常停止執行,致使週期性的任務再也不執行。

相關文章
相關標籤/搜索