ScheduledExecutorService執行週期性或定時任務

 ScheduledExecutorService擴展了ExecutorService接口,提供時間排程的功能。

 

schedule(Callable<V> callable, long delay, TimeUnit unit)

         創建並執行在給定延遲後啓用的 ScheduledFuture。

schedule(Runnable command, long delay, TimeUnit unit)

         創建並執行在給定延遲後啓用的一次性操作。

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnitunit)

         創建並執行一個在給定初始延遲後首次啓用的定期操作,後續操作具有給定的週期;也就是將在 initialDelay 後開始執行,然後在initialDelay+period 後執行,接着在 initialDelay + 2 * period 後執行,依此類推。

scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,TimeUnit unit)

         創建並執行一個在給定初始延遲後首次啓用的定期操作,隨後,在每一次執行終止和下一次執行開始之間都存在給定的延遲。

 

 

 

schedule方法被用來延遲指定時間來執行某個指定任務。如果你需要週期性重複執行定時任務可以使用scheduleAtFixedRate或者scheduleWithFixedDelay方法,它們不同的是前者以固定頻率執行,後者以相對固定頻率執行。

 

 

不管任務執行耗時是否大於間隔時間,scheduleAtFixedRate和scheduleWithFixedDelay都不會導致同一個任務併發地被執行。唯一不同的是scheduleWithFixedDelay是當前一個任務結束的時刻,開始結算間隔時間,如0秒開始執行第一次任務,任務耗時5秒,任務間隔時間3秒,那麼第二次任務執行的時間是在第8秒開始。

 

ScheduledExecutorService的實現類,是ScheduledThreadPoolExecutor。ScheduledThreadPoolExecutor對象包含的線程數量是沒有可伸縮性的,只會有固定數量的線程。不過你可以通過其構造函數來設定線程的優先級,來降低定時任務線程的系統佔用。

 

 

特別提示:通過ScheduledExecutorService執行的週期任務,如果任務執行過程中拋出了異常,那麼過ScheduledExecutorService就會停止執行任務,且也不會再週期地執行該任務了。所以你如果想保住任務都一直被週期執行,那麼catch一切可能的異常。

 

    

package test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* create at 11-10-14
* @author KETQI
* @category
*/
public class TestScheduledThreadPoolExecutor {
    private static SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args{
        //ScheduledExecutorService exec=Executors.newScheduledThreadPool(1);
        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
        /**
         *每隔一段時間打印系統時間,互不影響的<br/>
         * 創建並執行一個在給定初始延遲後首次啓用的定期操作,後續操作具有給定的週期;<br/>
         * 也就是將在 initialDelay 後開始執行,然後在initialDelay+period 後執行,<br/>
         * 接着在 initialDelay + 2 * period 後執行,依此類推。
         */
        exec.scheduleAtFixedRate(new Runnable() {
            public void run() {
                System.out.println(format.format(new Date()));
            }
        }, 1000, 5000, TimeUnit.MILLISECONDS);

        //開始執行後就觸發異常,next週期將不會運行
        exec.scheduleAtFixedRate(new Runnable() {
            public void run() {
                System.out.println("RuntimeException no catch,next time can't run");
                throw new RuntimeException();
            }
        }, 1000, 5000, TimeUnit.MILLISECONDS);

        //雖然拋出了運行異常,當被攔截了,next週期繼續運行
        exec.scheduleAtFixedRate(new Runnable() {
            public void run() {
                try{
                    throw new RuntimeException();
                }catch (Exception e){
                    System.out.println("RuntimeException catched,can run next");
                }
            }
        }, 1000, 5000, TimeUnit.MILLISECONDS);

        /**
         * 創建並執行一個在給定初始延遲後首次啓用的定期操作,<br/>
         * 隨後,在每一次執行終止和下一次執行開始之間都存在給定的延遲。
         */
        exec.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                System.out.println("scheduleWithFixedDelay:begin,"+format.format(new Date()));
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e{
                    e.printStackTrace();
                }
                System.out.println("scheduleWithFixedDelay:end,"+format.format(new Date()));
            }
        },1000,5000,TimeUnit.MILLISECONDS);

        /**
         * 創建並執行在給定延遲後啓用的一次性操作。
         */
        exec.schedule(new Runnable() {
            public void run() {
                System.out.println("The thread can only run once!");
            }
        },5000,TimeUnit.MILLISECONDS);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章