ScheduledExecutorService 介面



java.util.concurrent.ScheduledExecutorService 介面是 ExecutorService 介面的子介面,支援任務的未來和/或週期性執行。

ScheduledExecutorService 方法

序號 方法及描述
1

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

建立並執行一個 ScheduledFuture,在給定的延遲後啟用。

2

ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)

建立並執行一個一次性動作,在給定的延遲後啟用。

3

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

建立並執行一個週期性動作,首先在給定的初始延遲後啟用,然後以給定的週期重複執行;也就是說,執行將在 initialDelay 後開始,然後是 initialDelay+period,然後是 initialDelay + 2 * period,依此類推。

4

ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

建立並執行一個週期性動作,首先在給定的初始延遲後啟用,然後在一次執行終止和下一次執行開始之間以給定的延遲重複執行。

示例

以下 TestThread 程式展示了在基於執行緒的環境中使用 ScheduledExecutorService 介面。

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

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

      final ScheduledFuture<?> beepHandler = 
         scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);

      scheduler.schedule(new Runnable() {

         @Override
         public void run() {
            beepHandler.cancel(true);
            scheduler.shutdown();			
         }
      }, 10, TimeUnit.SECONDS);
   }

   static class BeepTask implements Runnable {
      
      public void run() {
         System.out.println("beep");      
      }
   }
}

這將產生以下結果。

輸出

beep
beep
beep
beep
廣告