首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

详解scheduleAtFixedRate与scheduleWithFixedDelay原理

我们熟悉的 scheduleAtFixedRate、scheduleWithFixedDelay 方法,还有 cron 表达式,他们的主要区别在于计算下一次调度时间的逻辑不同,这样导致调度的效果有很大的区别...我们先来看看类图: 由类图可知,ScheduledThreadPoolExecutor 继承至线程池 ThreadPoolExecutor,并且它提供了 schedule、scheduleAtFixedRate...& scheduleWithFixedDelay scheduleAtFixedRate 方法的逻辑很简单,只是构造了一个 ScheduledFutureTask 任务,然后丢到延迟队列中,具体的代码如下所示...> scheduleAtFixedRate(Runnable command, long initialDelay...前面也说了,scheduleAtFixedRate、scheduleWithFixedDelay 这两个 api 方法传递的 period 值是有正负之分的,因此计算下一次调度时间也是有差异的,具体代码如下

3.1K20
您找到你想要的搜索结果了吗?
是的
没有找到

面试突击34:如何使用线程池执行定时任务?

使用 scheduleAtFixedRate 方法执行定时任务,执行多次定时任务。 使用 scheduleWithFixedDelay 方法执行定时任务,执行多次定时任务。...2.scheduleAtFixedRate scheduleAtFixedRate 方法可以执行多次定时任务,此方法需要 4 个参数: 第 1 个参数:传递一个任务,Runnable 或 Callable...3.scheduleWithFixedDelay scheduleWithFixedDelay 方法的使用和 scheduleAtFixedRate 类似,但执行效果完全不同,这个很容易理解如果效果一样就不用创建两个方法了...scheduleWithFixedDelay 方法是在方法执行完成之后,再隔 N 秒执行下一个定时任务,和 scheduleAtFixedRate 的固定时间执行不同,scheduleWithFixedDelay...使用 scheduleAtFixedRate 方法执行定时任务,执行多次定时任务,它的执行时间间隔是固定的,不受定时任务执行时长影响(定时任务时间间隔 > 任务执行时间)。

48510

几种定时任务(Timer、TimerTask、ScheduledFuture)的退出—结合真实案例【JAVA并发】

需求说明:定时更新正在生成的文件大小和状态【进行中、失败、完成】,如果文件生成完成,则退出【CoderBaby】 调度可以用Timer 【调用schedule()或者scheduleAtFixedRate...logger.warn("Catch exception : " + e.toString()); } } }  通过scheduleAtFixedRate...接口来调用(设置时间间隔和且第一次执行的延迟时间) scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(...特别说明: 关于schedule(时间基准:运行的实际时间)和scheduleAtFixedRate(时间基准:理论时间点)的区别: scheduleAtFixedRate调度一个task,在delay...schedule在计算下一次执行的时间的时候,是通过当前时间(在任务执行前得到) + 时间片,而scheduleAtFixedRate方法是通过当前需要执行的时间(也就是计算出现在应该执行的时间)+ 时间片

1.6K21

Java中定时任务的6种实现方式,你知道几种?

此时,你是否疑惑schedule与scheduleAtFixedRate效果一样,为什么提供两个方法,它们有什么区别?...schedule与scheduleAtFixedRate区别 在了解schedule与scheduleAtFixedRate方法的区别之前,先看看它们的相同点: 任务执行未超时,下次执行时间 = 上次执行开始时间...scheduleAtFixedRate保持执行频率的稳定 scheduleAtFixedRate在反复执行一个task的计划时,每一次执行这个task的计划执行时间在最初就被定下来了,也就是scheduledExecutionTime...如果用一句话来描述任务执行超时之后schedule和scheduleAtFixedRate的区别就是:schedule的策略是错过了就错过了,后续按照新的节奏来走;scheduleAtFixedRate...scheduleAtFixedRate方法 scheduleAtFixedRate方法,按指定频率周期执行某个任务。定义及参数说明: public ScheduledFuture<?

2.2K30

Java 定时器 Timer 的使用.

,long period) 区别 相同点: 1、方法schedule 和方法 scheduleAtFixedRate 都会按顺序执行,所以不用考虑非线程安全的情况。...2、方法schedule 和方法 scheduleAtFixedRate 如果执行任务的时间没有被延迟,那么下一次任务的执行时间参考的是上一次的任务的"开始"时的时间来计算的。...3、方法schedule 和方法 scheduleAtFixedRate 如果执行任务的时间被延迟了,那么下一次任务的执行时间参考的是上一次任务"结束"时的时间来计算。 ? ?...不同点:       方法schedule 和方法 scheduleAtFixedRate 在使用上基本没什么差别,就是 scheduleAtFixedRate 具有追赶执行性,什么意思呢?...就是如果任务 在周期性运行过程中被打断了,scheduleAtFixedRate 会尝试把之前落下的任务补上运行。而schedule就不管了,接着运行接下来的任务就行了,可以参考这篇博客,写的很生动。

1.1K90
领券