Java ~ Executor ~ ScheduledExecutorService【源码】

前言


 相关系列

 涉及内容

一 ScheduledExecutorService(调度执行器服务)接口源码及机制详解


 接口

    ScheduledExecutorService(调度执行器服务)接口是ExecutorService (执行器服务)接口的子接口,在其的基础再次新增了“调度”的概念。所谓调度可以理解为定时执行,即令任务在指定时间点被执行,而非在任务可被执行的情况下被立即执行。

    调度执行器服务接口将“调度”概念细分为了“延迟”与“周期”两个概念。“延迟”概念很好理解,即是否需要将任务的执行时间在其可被执行的时间点上延迟指定时间。这种延迟是人为规定的,与任务的执行机制无关。而大部分执行器由于自身任务执行机制的原因虽然也可能造成延迟,但这种延迟并非人为规定,因此与“延迟”概念没有关系。由此可知,虽然调度执行器服务接口支持指定任务的延迟时间,但在任务正式执行时其实际延迟时间可能比指定延迟时间更长(也可能更短)。此外调度执行器服务接口支持零/负延迟,当延迟被指定为该类型的值时任务会被立即执行。而关于“周期”的概念很也好理解,即任务是否需要重复执行,是则任务会以指定周期时间周期性执行;否则只会单次执行。通过对这两种概念进行组合,调度执行器服务接口可实现无延迟单次执行/有延迟单次执行/无延迟周期执行/有延迟周期执行四种任务调度形式。

/**
 * An {@link ExecutorService} that can schedule commands to run after a given delay, or to execute periodically.
 * 一个可以调度命令在指定延迟后运行,或周期性执行的执行器服务。
 * <p>
 * The {@code schedule} methods create tasks with various delays and return a task object that can be used to cancel or
 * check execution. The {@code scheduleAtFixedRate} and {@code scheduleWithFixedDelay} methods create and execute
 * tasks that run periodically until cancelled.
 * schedule()方法随着可变的延迟创建任务并返回一个可用于取消和检查执行的任务对象。scheduleAtFixedRate()和
 * scheduleWithFixedDelay()方法会周期性地创建及执行任务直至取消。
 * <p>
 * Commands submitted using the {@link Executor#execute(Runnable)} and {@link ExecutorService} {@code submit} methods
 * are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in
 * {@code schedule} methods, and are treated as requests for immediate execution.
 * 使用execute和submit方法递交的命令随着0延迟请求调度。0和负延迟(但不可以是周期)在调度方法中也允许,并且被作为
 * 立即执行请求对待。
 * <p>
 * All {@code schedule} methods accept <em>relative</em> delays and periods as arguments, not absolute times or dates.
 * It is a simple matter to transform an absolute time represented as a {@link Date} to the required form. For example, to
 * schedule at a certain future {@code date}, you can use:
 * {@code schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)}.
 * Beware however that expiration of a relative delay need not coincide with the current {@code Date} at which the task
 * is enabled due to network time synchronization protocols, clock drift, or other factors.
 * 所有调度方法都接受相关联的延迟和周期作为参数【即存在针对各种时间格式的重载方法】,不单纯是时间或日期。这是个
 * 转变单纯时间作为日期用于需要格式的简单问题。例如,为了在某个未来时间调度,你可以使用:
 * schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)
 * 此外注意:由于网络时间同步规约,时钟漂移,或者其它因素,相对延迟的到期日期不必与启用任务的当前日期一致【即实际
 * 执行时间可能与计划执行时间存在误差...妈的说的这么晦涩是想难到谁?】。
 * <p>
 * The {@link Executors} class provides convenient factory methods for the ScheduledExecutorService implementations
 * provided in this package.
 * Executors类提供便利的调度执行器服务实现(在当前包中实现)的工厂方法。
 * <h3>Usage Example</h3>
 * 使用模板
 * <p>
 * Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
 * 这是一个随着方法建立一个调度线程池执行器来在一小时内每十秒鸣响的类:
 * <pre> {@code
 * import static 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);
 *   }
 * }}</pre>
 *
 * @author Doug Lea
 * @since 1.5
 */
public interface ScheduledExecutorService extends ExecutorService {
    ...
}

 方法


  • public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) —— 调度 —— 向当前调度执行器服务递交在指定延迟后执行的可运行/任务,并返回追踪/获取可运行/任务执行状态/结果的调度未来。由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果的变量,因此调度未来实际无法获取可运行/任务的执行结果,故而该方法返回的调度未来的get()方法将永远返回null。
    /**
     * Creates and executes a one-shot action that becomes enabled after the given delay.
     * 创建和执行一个单在指定延迟之后可用的单次活动。
     *
     * @param command the task to execute 用于执行的任务
     * @param delay   the time from now to delay execution 用于延迟执行的基于当前的时间
     * @param unit    the time unit of the delay parameter 延迟参数的时间单位
     * @return a ScheduledFuture representing pending completion of the task and whose {@code get()} method will return
     * {@code null} upon completion
     * 一个调度未来代表任务的待定完成并且get()方法在完成后将返回null
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法被调度执行
     * @throws NullPointerException       if command is null
     *                                    空指针异常:如果命令为null
     * @Description: ------------------------------------------------------------- 名称 -------------------------------------------------------------
     * 调度
     * @Description: ------------------------------------------------------------- 作用 -------------------------------------------------------------
     * 向当前调度执行器服务递交在指定延迟后执行的可运行/任务,并返回追踪/获取可运行/任务执行状态/结果的调度未来。
     * 由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果的变量,因此调度未来实际无法获取可运行/任务的执
     * 行结果,故而该方法返回的调度未来的get()方法将永远返回null。
     * @Description: ------------------------------------------------------------- 逻辑 -------------------------------------------------------------
     * ----
     */
    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
  • public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) —— 调度 —— 向当前调度执行器服务递交在指定延迟后执行的可调用/任务,并返回追踪/获取可调用/任务执行状态/结果的调度未来。
    /**
     * Creates and executes a ScheduledFuture that becomes enabled after the given delay.
     * 创建和执行一个在指定延迟后可用的调度未来。
     *
     * @param callable the function to execute 用于指定的功能
     * @param delay    the time from now to delay execution 用于延迟执行的基于当前时间的时间
     * @param unit     the time unit of the delay parameter 延迟参数的时间单位
     * @param <V>      the type of the callable's result 可调用结果的类型
     * @return a ScheduledFuture that can be used to extract result or cancel
     * 一个可用于提取结果或取消的调度未来
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法被调度执行
     * @throws NullPointerException       if command is null
     *                                    空指针异常:如果命令为null
     * @Description: ------------------------------------------------------------- 名称 -------------------------------------------------------------
     * 调度
     * @Description: ------------------------------------------------------------- 作用 -------------------------------------------------------------
     * 向当前调度执行器服务递交在指定延迟后执行的可调用/任务,并返回追踪/获取可调用/任务执行状态/结果的调度未来。
     * @Description: ------------------------------------------------------------- 逻辑 -------------------------------------------------------------
     * ----
     */
    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
  • public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) —— 按固定速率调度 —— 向当前调度执行器服务递交在指定初始延迟后按指定周期周期性执行的可运行/任务,并返回追踪/获取可运行/任务执行状态/结果的调度未来。由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果的变量,因此调度未来实际无法获取可运行/任务的执行结果,故而该方法返回的调度未来的get()方法将永远返回null。但又因为该方法递交的可运行/任务将在自身没有被取消/执行中没有抛出异常/当前调度执行器服务没有被终止的情况下永远周期性地执行下去,因此调度未来的get()方法要么因为上述情况抛出异常,要么因为无法获取到结果而无限等待。此外,即使可运行/任务的执行时间超过周期,下次执行依然会在距离上次执行开始时间点的指定周期后开始,并且上次执行会被取消(虽然可能无法响应)。
    /**
     * 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 {@code initialDelay} then {@code initialDelay+period}, then
     * {@code 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.
     * 创建和执行一个在指定初始延迟之后,并随着指定周期可用的周期性活动;该执行将在初始延迟之后的initialDelay+period
     * 时间,initialDelay + 2 * period时间开始,等等。如果任意【一次】任务的执行遭遇一场,随后执行将被禁止。此外,任务
     * 将只能通过取消或执行器的终止而终止。如果任意当前任务的执行占有比它的周期更长的时间,那么随后执行可能开始的较
     * 晚,但不会并发地执行【一个任务一个时间只能被一条线程执行】。
     *
     * @param command      the task to execute 用于执行的任务
     * @param initialDelay the time to delay first execution 用于延迟首次执行的时间
     * @param period       the period between successive executions 介于两次连续执行的周期
     * @param unit         the time unit of the initialDelay and period parameters 初始延迟和周期参数的时间单位
     * @return a ScheduledFuture representing pending completion of the task, and whose {@code get()} method will throw an
     * exception upon cancellation
     * 一个调度未来代表任务的等待执行,并且get()方法将在取消后抛出异常。
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法被调度执行
     * @throws NullPointerException       if command is null
     *                                    空指针异常:如果命令为null
     * @throws IllegalArgumentException   if period less than or equal to zero
     *                                    非法参数异常:如果周期小于等于0
     * @Description: ------------------------------------------------------------- 名称 -------------------------------------------------------------
     * 按固定速率调度
     * @Description: ------------------------------------------------------------- 作用 -------------------------------------------------------------
     * 向当前调度执行器服务递交在指定初始延迟后按指定周期周期性执行的可运行/任务,并返回追踪/获取可运行/任务执行状
     * 态/结果的调度未来。由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果的变量,因此调度未来实际无法获
     * 取可运行/任务的执行结果,故而该方法返回的调度未来的get()方法将永远返回null。但又因为该方法递交的可运行/任务将
     * 在自身没有被取消/执行中没有抛出异常/当前调度执行器服务没有被终止的情况下永远周期性地执行下去,因此调度未来
     * 的get()方法要么因为上述情况抛出异常,要么因为无法获取到结果而无限等待。此外,即使可运行/任务的执行时间超过周
     * 期,下次执行依然会在距离上次执行开始时间点的指定周期后开始,并且上次执行会被取消(虽然可能无法响应)。
     * @Description: ------------------------------------------------------------- 逻辑 -------------------------------------------------------------
     * ----
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
  • public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) —— 随固定延迟调度 —— 向当前调度执行器服务递交在指定初始延迟后按指定延迟周期性执行的可运行/任务,并返回追踪/获取可运行/任务执行状态/结果的调度未来。由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果的变量,因此调度未来实际无法获取可运行/任务的执行结果,故而该方法返回的调度未来的get()方法将永远返回null。但又因为该方法递交的可运行/任务将在自身没有被取消/执行中没有抛出异常/当前调度执行器服务没有被终止的情况下永远周期性地执行下去,因此调度未来的get()方法要么因为上述情况抛出异常,要么因为无法获取到结果而无限等待。此外,如果可运行/任务的执行时间超过周期,则下次执行会在距离上次执行结束时间点的指定延迟后开始。
    /**
     * 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.
     * 创建并执行一个在指定初始延迟之后可用,并随着指定介于首次执行结束和下次执行开始的延迟执行的周期型活动。如果
     * 任意【一次】任务的执行遭遇一场,随后执行将被禁止。此外,任务将只能通过取消或执行器的终止而终止。
     *
     * @param command      the task to execute 用于执行的任务
     * @param initialDelay the time to delay first execution 用于延迟首次执行的时间
     * @param delay        the delay between the termination of one execution and the commencement of the next
     *                     介于首次执行终止何下次执行开始的延迟
     * @param unit         the time unit of the initialDelay and period parameters 初始延迟和周期参数的时间单位
     * @return a ScheduledFuture representing pending completion of the task, and whose {@code get()} method will throw an
     * exception upon cancellation
     * 一个调度未来代表任务的等待执行,并且get()方法将在取消后抛出异常。
     * @throws RejectedExecutionException if the task cannot be scheduled for execution
     *                                    拒绝执行异常:如果任务无法被调度执行
     * @throws NullPointerException       if command is null
     *                                    空指针异常:如果命令为null
     * @throws IllegalArgumentException   if period less than or equal to zero
     *                                    非法参数异常:如果周期小于等于0
     * @Description: ------------------------------------------------------------- 名称 -------------------------------------------------------------
     * 随固定延迟调度
     * @Description: ------------------------------------------------------------- 作用 -------------------------------------------------------------
     * 向当前调度执行器服务递交在指定初始延迟后按指定延迟周期性执行的可运行/任务,并返回追踪/获取可运行/任务执行状
     * 态/结果的调度未来。由于在递交可运行/任务时没有传入用于承载可运行/任务执行结果的变量,因此调度未来实际无法获
     * 取可运行/任务的执行结果,故而该方法返回的调度未来的get()方法将永远返回null。但又因为该方法递交的可运行/任务将
     * 在自身没有被取消/执行中没有抛出异常/当前调度执行器服务没有被终止的情况下永远周期性地执行下去,因此调度未来
     * 的get()方法要么因为上述情况抛出异常,要么因为无法获取到结果而无限等待。此外,如果可运行/任务的执行时间超过周
     * 期,则下次执行会在距离上次执行结束时间点的指定延迟后开始。
     * @Description: ------------------------------------------------------------- 逻辑 -------------------------------------------------------------
     * ----
     */
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

说淑人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值