当前位置: 首页 > news >正文

Java Executor ScheduledExecutorService 源码

前言


 相关系列

  • 《Java & Executor & 目录》
  • 《Java & Executor & ScheduledExecutorService & 源码》
  • 《Java & Executor & ScheduledExecutorService & 总结》
  • 《Java & Executor & ScheduledExecutorService & 问题》
     

 涉及内容

  • 《Java & Executor & 总结》
  • 《Java & Executor & ExecutorService & 总结》
     
     

概述


 简介

在这里插入图片描述

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

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

源码


/** ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.*********************//******* Written by Doug Lea with assistance from members of JCP JSR-166* Expert Group and released to the public domain, as explained at* http://creativecommons.org/publicdomain/zero/1.0/*/package juc;import java.util.Date;/*** 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 {/*** 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);/*** 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);/*** 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);/*** 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);}
http://www.lryc.cn/news/473882.html

相关文章:

  • 【力扣 + 牛客 | SQL题 | 每日6题】牛客SQL热题 + 力扣hard
  • 前端常见错误
  • Edge 浏览器插件开发:图片切割插件
  • 银河麒麟v10 xrdp安装
  • Leetcode 删除有序数组中的重复项 Ⅱ
  • 大模型学习笔记------什么是大模型
  • 【unique_str 源码学习】
  • flask第一个应用
  • 华为OD机试真题(Python/JS/C/C++)- 考点 - 细节
  • 【C++刷题】力扣-#628-三个数的最大乘积
  • Java项目实战II基于Java+Spring Boot+MySQL的工程教育认证的计算机课程管理平台(源码+数据库+文档)
  • 基于微信小程序实现信阳毛尖茶叶商城系统设计与实现
  • 设计一个灵活的RPC架构
  • 大数据计算里的Broadcast Hash Join/Shuffle Hash Join/Sort Merge Join
  • Java - 手写识别; 如何用spring ai和大模型做手写识别教程
  • 【Linux】用户权限管理:创建受限用户并配置特定目录访问权限
  • pgsql表分区和表分片设计
  • 灵动AI ——视频创作新引擎 开启视觉奇幻之旅
  • AI设计、作图、画画工具哪个好用?看完这篇你就知道怎么选了
  • 【python ASR】win11-从0到1使用funasr实现本地离线音频转文本
  • myqld二进制安装和破解数据库密码(linux)
  • 防重方案-订单防重方案笔记
  • HTML、JavaScript和CSS实现注册页面设计
  • Counter对象的使用样例
  • 大模型中的token是什么;常见大语言模型的 token 情况
  • Python小白学习教程从入门到入坑------第十七课 内置函数拆包(语法基础)
  • 动态规划 —— 路径问题-最小路径和
  • 《链表篇》---删除链表的倒数第N个节点(中等)
  • duilib 进阶 之 TileListBox 列表
  • Web应用安全—信息泄露