目录

ScheduledExecutorService

java.util.concurrent.ScheduledExecutorService接口是ExecutorService接口的子接口,支持将来和/或定期执行任务。

ScheduledExecutorService方法

Sr.No. 方法和描述
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)

创建并执行一个周期性动作,该动作在给定的初始延迟之后首先被启用,并且随后在一次执行的终止和下一次执行的开始之间给定延迟。

例子 (Example)

以下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");      
      }
   }
}

这将产生以下结果。

输出 (Output)

beep
beep
beep
beep
↑回到顶部↑
WIKI教程 @2018