源码解读ExcutorService之ScheduledExecutorService

ScheduledExecutorService是ExecutorService的子类,提供任务调度功能,可实现延迟执行和定期执行任务。它允许创建带有特定延迟或周期的任务,并通过ScheduledFuture进行管理。文章介绍了schedule、scheduleAtFixedRate和scheduleWithFixedDelay等方法的使用,以及如何处理任务异常和取消任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ScheduledExecutorService继承自ExcutorService,也就是它是一种线程池,它不仅能实现任务的跟踪与管理,还能定时、定频执行任务。

文档渣翻
  • An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

它是一种可以任务调度的线程池,你可以使其延时、或者定频执行。

  • 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.

你可以指定任意的延迟来使用schedule方法以创建一个任务,它会返回一个task对象用以取消或者跟踪执行情况。scheduleAtFixedRate、scheduleWithFixedDelay 方法可以创建一个定频任务,直到你取消它。

  • 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.

你可以使用execute方法或者submit方法来提交一个任务,任务会被零延迟地立刻执行。你可以在schedule方法,也就是创建任务时指定零延迟或者负延迟,它们会被当作立即执行的任务。

  • 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 java.util.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.

所有的schedule方法都可以接收 延迟定频 作为参数,参数不是一个绝对的时间或者日期。将一个绝对的时间转换为需要的形式是很容易实现的。比方说,要实现未来某个时刻的任务调度,我们可以调用

    schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)

但要注意,这个延迟到期时,可能因为各种原因,例如网络时间同步协议、时间不同步等等、导致真正的延迟时间和你设定的不一致。(比如说现在是9点,我设置了10点.getTime() - System.currentTimeMillis()的delay,这时候服务器上的时间是9点50分,任务延迟10分钟就会执行,而不是预想的一小时。)

  • The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

在这个包中,Executors这个类提供了很多方便的Factory方法实现了ScheduledExecutorService,比如说:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值