Java指定週期執行執行緒

Nick-Huang發表於2015-05-06

使用Java的API可以指定週期地啟動執行緒。


設定從現在開始(從0秒開始),每隔10秒,啟動一個執行緒

ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleAtFixedRate(new PeroidSchedualRunnable(), 0, 10, TimeUnit.SECONDS);

執行的執行緒為

package com.nicchagil.fsl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class PeroidSchedualRunnable implements Runnable {

    public static int count = 0;

    public void run() {
        // Used to simulate the cost of business
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("PeroidSchedualRunnable run " + count++ + " at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

}

觀看日誌可知,其每隔10秒就執行一次

PeroidSchedualRunnable run 0 at 2015-05-06 18:02:37
PeroidSchedualRunnable run 1 at 2015-05-06 18:02:47
PeroidSchedualRunnable run 2 at 2015-05-06 18:02:57

另外,ScheduledExecutorService的另一方法(scheduleWithFixedDelay)稍有不同,此方法設定的是延遲的時間。而scheduleAtFixedRate設定的指定的頻率。

ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleWithFixedDelay(new DelaySchedualRunnable(), 0, 10, TimeUnit.SECONDS);

觀看日誌可知,第0次於18:05:06執行完畢,此時延遲10秒,然後執行第1次,執行完畢後再延遲10秒,如此類推。

DelaySchedualRunnable run 0 at 2015-05-06 18:05:06
DelaySchedualRunnable run 1 at 2015-05-06 18:05:21
DelaySchedualRunnable run 2 at 2015-05-06 18:05:36

注意:如果過程中異常沒有正常處理(被虛擬機器捕獲),將會停止執行,不再繼續週期呼叫。

感覺越說越不好,乾脆引用API的原文:

  • ScheduledExecutorService.scheduleAtFixedRate:

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 initialDelay then initialDelay+period, then initialDelay + 2 * period, 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.

  • ScheduledExecutorService.scheduleWithFixedDelay:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. 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.

相關文章