ScheduledExecutorService執行定時任務接口

ScheduledExecutorService接口
在ExecutorService的基礎上,ScheduledExecutorService提供了按時間安排執行任務的功能,它提供的方法主要有:
schedule(task,initDelay):安排所提交的Callable或Runnable任務在initDelay指定的時間後執行。 scheduleAtFixedRate():安排所提交的Runnable任務按指定的間隔重複執行 scheduleWithFixedDelay():安排所提交的Runnable任務在每次執行完後,等待delay所指定的時間後重復執行。
代碼:ScheduleExecutorService的例子

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceTest
{
       public static void main(String[] args) throws InterruptedException,ExecutionException
       {
              //*1
               ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
               //*2
               Runnable task1=new Runnable()
               {
                    public void run()
                    {
                       System.out.println("Taskrepeating.");
                    }
               };
               //*3
               final ScheduledFuture future1=service.scheduleAtFixedRate(task1,0,1,TimeUnit.SECONDS);
               //*4
               ScheduledFuture future2=service.schedule(new Callable()
             {
                    public String call()
                    {
                            future1.cancel(true);
                            return "taskcancelled!";
                    }
               },10,TimeUnit.SECONDS);
               System.out.println(future2.get());
    //*5
    service.shutdown();
   }
}

這個例子有兩個任務,第一個任務每隔一秒打印一句“Taskrepeating”,第二個任務在5秒鐘後取消第一個任務。

*1:初始化一個ScheduledExecutorService對象,這個對象的線程池大小爲2。
*2:用內函數的方式定義了一個Runnable任務。
*3:調用所定義的ScheduledExecutorService對象來執行任務,任務每秒執行一次。能重複執行的任務一定是Runnable類型。注意我們可以用TimeUnit來制定時間單位,這也是Java5.0裏新的特徵,5.0以前的記時單位是微秒,現在可精確到奈秒。
*4:調用ScheduledExecutorService對象來執行第二個任務,第二個任務所作的就是在5秒鐘後取消第一個任務。
*5:關閉服務。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章