欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ScheduledExecutorService

程序员文章站 2022-05-14 21:56:36
...

Interface ScheduledExecutorService

All Superinterfaces:
Executor, ExecutorService
All Known Implementing Classes:
ScheduledThreadPoolExecutor


public interface ScheduledExecutorService extends ExecutorService

An ExecutorService that can schedule commands to run after a given delay(给定延迟), or to execute periodically(定期)(一个ExecutorService,可以调度命令在给定的延迟之后运行或定期执行).
The schedule methods create tasks with various(各个) delays(各种延迟) and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically(定期) until cancelled.

Commands submitted using the Executor.execute(Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative(负) delays (but not periods(周期)) are also allowed in schedule methods, and are treated as requests for immediate(即时,直接,立刻) execution.

All schedule methods accept relative(相对的) delays(延迟) and periods(周期) as arguments, not absolute times or dates. It is a simple matter to transform(转换) an absolute time represented(代表) as a Date to the required form(将代表作为日期的绝对时间转换为所需的形式是一件简单的事情). For example, to schedule at a certain(某) future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)(例如,要在某个未来日期安排,可以使用). Beware however that(请注意) expiration(满期,过期) of a relative delay need not coincide(重合) with the current Date at which the task is enabled due(应有) to network time synchronization protocols(协议), clock drift, or other factors(请注意,相对延迟的到期不需要重合与任务启用的当前日期到网络时间同步协议,时钟漂移,或其他因素。).

The Executors class provides convenient(方便) factory methods for the ScheduledExecutorService implementations provided in this package.

Usage Example

Here is a class with a method that sets up(设置) a ScheduledExecutorService to beep(响铃) every ten seconds for an hour:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
   private final ScheduledExecutorService scheduler =
     Executors.newScheduledThreadPool(1);

   public void beepForAnHour() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); }
     };
     final ScheduledFuture<?> beeperHandle =
       scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
     scheduler.schedule(new Runnable() {
       public void run() { beeperHandle.cancel(true); }
     }, 60 * 60, SECONDS);
   }
 }

Since:
1.5

Methods inherited from interface java.util.concurrent.ExecutorService

awaitTermination, invokeAll, invokeAll, invokeAny, invokeAny, isShutdown, isTerminated, shutdown, shutdownNow, submit, submit, submit

Methods inherited from interface java.util.concurrent.Executor

execute

Method Detail

schedule

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

Creates and executes a one-shot(一次性) action that becomes enabled after the given delay(创建并执行在给定延迟后启用的一次性动作。).
Parameters:
command - the task to execute
delay - the time from now to delay execution
unit - the time unit of the delay parameter
Returns:
a ScheduledFuture representing(表示) pending(等待) completion完成 of the task and whose get() method will return null upon completion(一个ScheduledFuture代表待完成的任务,其get()方法将在完成后返回null)
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if command is null

schedule

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

Creates and executes a ScheduledFuture that becomes enabled after the given delay.
Type Parameters:
V - the type of the callable’s result
Parameters:
callable - the function to execute
delay - the time from now to delay execution
unit - the time unit of the delay parameter
Returns:
a ScheduledFuture that can be used to extract(提取) result or cancel
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if callable is null

scheduleAtFixedRate

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

Creates and executes a periodic(定期) action that becomes enabled first after the given initial delay, and subsequently(以后) with the given period(创建并执行在给定的初始延迟之后首先启用的定期动作,随后在给定的周期内); that is executions will commence(启动) after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters(遭遇) an exception, subsequent(以后) executions are suppressed(抑制). Otherwise(否则), the task will only terminate(终止) via(通过) cancellation(消除) or termination(终止) of the executor. If any execution of this task takes longer than its period, then subsequent(随后) executions may start late, but will not concurrently execute(如果任务执行时间超过其周期,则后续(随后)执行可能会迟到,但不会同时执行).
Parameters:
command - the task to execute
initialDelay - the time to delay first execution
period - the period between successive executions
unit - the time unit of the initialDelay and period parameters
Returns:
a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if command is null
IllegalArgumentException - if period less than or equal to zero

scheduleWithFixedDelay

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

Creates and executes a periodic(定期) action that becomes(变成) enabled first after the given initial(初始) delay, and subsequently(以后) with the given delay between the termination(终止) of one execution and the commencement of the next(创建并执行在给定的初始延迟之后成为的定期动作,随后以一个执行的终止和下一个执行的开始之间的给定延迟). If any execution of the task encounters(遭遇) an exception, subsequent(随后) executions are suppressed(抑制). Otherwise, the task will only terminate(终止) via(通过) cancellation(取消) or termination(终止) of the executor.
Parameters:
command - the task to execute
initialDelay - the time to delay first execution
delay - the delay between the termination of one execution and the commencement of the next
unit - the time unit of the initialDelay and delay parameters
Returns:
a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if command is null
IllegalArgumentException - if delay less than or equal to zero

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html