scheduleatfixedrate的简单介绍

http://www.itjxue.com  2023-01-27 07:47  来源:未知  点击次数: 

scheduleWithFixedDelay 和 scheduleAtFixedRate 的区别

ScheduledExecutorService#scheduleAtFixedRate() 指的是“以固定的频率”执行,period(周期)指的是两次成功执行之间的时间

比如, scheduleAtFixedRate(command, 5, 2, second) ,第一次开始执行是5s后,假如执行耗时1s,那么下次开始执行是7s后,再下次开始执行是9s后

而ScheduledExecutorService#scheduleWithFixedDelay() 指的是“以固定的延时”执行,delay(延时)指的是一次执行终止和下一次执行开始之间的延迟

scheduleWithFixedDelay(command, 5, 2, second) ,第一次开始执行是5s后,假如执行耗时1s,执行完成时间是6s后,那么下次开始执行是8s后,再下次开始执行是11s后

scheduleAtFixedRate与scheduleWithFixedDelay区别

先来看字面意思:

1、scheduleAtFixedRate 方法,顾名思义,它的方法名称的意思是:已固定的频率来执行某项计划(任务)。

2、scheduleWithFixedDealy,相对固定的延迟后,执行某项计划。

单从它们的字面来看,还是让人困惑,跟TC的管猿似的,文字游戏。

还是比较简单明了的描述比较好:第一个方法是固定的频率来执行某项计划,它不受计划执行时间的影响。到时间,它就执行。

而第二个方法,相对固定,据鄙人理解,是相对任务的。即无论某个任务执行多长时间,等执行完了,我再延迟指定的时间。也就是第二个方法,它受计划执行时间的影响。

不知道诸位看懂了没。

我再举一个简单的例子吧。

比方说:

某航空公司的航班:对于普通老百姓来说,不管你是在路上堵车了,还是正在跑呢,它是按时按点飞的。你的延误耽误不了飞机的起飞。这就是第一个方法。

我的理解:

? ? ? ? ?ScheduledExecutorServices 中的cheduleAtFixedRate就是按点跑,也就是规定频率为1h,那么好,A任务开始执行,过来一个小时后,不管A是否执行完,都开启B任务;而scheduleWithFixedDealy却是需要在A任务执行完后,在经过1小时后再去执行B任务;

schedule和scheduleAtFixedRate的区别

scheduleAtFixedRate() 与 schedule() 的区别

scheduleAtFixedRate() 与 schedule()看起来功能很像,其实不然。

scheduleAtFixedRate()的API说明有这样一段话:

If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period.

翻译过来的大概意思是:如果任务比较复杂,或者由于任何原因(如垃圾回收或其他后台活动)而延迟了某次执行,则scheduleAtFixedRate方法将快速连续地出现两次或更多的执行,从而使后续执行能够“追赶上来”。从长远看,执行的频率很接近指定的周期。

而schedule()的API说明是这样写的:

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period.

翻译过来大概意思是:如果任务比较复杂,或者由于任何原因(如垃圾回收或其他后台活动)而延迟了某次执行,则接下来的任务也会被延迟,从长远看,schedule执行的频率将稍微比指定的周期要低点。

(责任编辑:IT教学网)

更多

推荐Flash教程文章