概述
ScheduledExecutorService可以在给定的延迟后运行或者定期的执行任务。
ScheduledThreadPoolExecutor继承自ThreadPoolExecutor同时实现了ScheduledExecutorService接口,在ThreadPoolExecutor的基础上支持执行延迟任务或者周期性的任务。
ScheduledExecutorService接口
ScheduledExecutorService的接口集成关系:
Executor
|---ExecutorService
|--ScheduledExecutorService
ScheduledExecutorService除了父接口定义的方法之外同时新增了四个方法:
- ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); 创建并执行在给定延迟后启用的 命令。
- ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit); 创建并执行给定延迟后执行的命令,可以有返回值。
- ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); 创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在initialDelay后开始执行,然后在initialDelay+period 后执行,接着在initialDelay + 2 * period 后执行,依此类推。
- ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); 创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。