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执行的频率将稍微比指定的周期要低点。
scheduleAtFixedRate和scheduleWithFixedDelay 区别
先来看字面意思:
1、scheduleAtFixedRate 方法,顾名思义,它的方法名称的意思是:已固定的频率来执行某项计划(任务)。
2、scheduleWithFixedDealy,相对固定的延迟后,执行某项计划。
单从它们的字面来看,还是让人困惑,跟TC的管猿似的,文字游戏。
还是比较简单明了的描述比较好:第一个方法是固定的频率来执行某项计划,它不受计划执行时间的影响。到时间,它就执行。
而第二个方法,相对固定,据鄙人理解,是相对任务的。即无论某个任务执行多长时间,等执行完了,我再延迟指定的时间。也就是第二个方法,它受计划执行时间的影响。
不知道诸位看懂了没。

我再举一个简单的例子吧。
比方说:
某航空公司的航班:对于普通老百姓来说,不管你是在路上堵车了,还是正在跑呢,它是按时按点飞的。你的延误耽误不了飞机的起飞。这就是第一个方法。
我的理解:
ScheduledExecutorServices 中的cheduleAtFixedRate就是按点跑,也就是规定频率为1h,那么好,A任务开始执行,过来一个小时后,不管A是否执行完,都开启B任务;而scheduleWithFixedDealy却是需要在A任务执行完后,在经过1小时后再去执行B任务;
scheduleWithFixedDelay 和 scheduleAtFixedRate 的区别
Executors提供的线程池ScheduledExecutorService中有两个方法,scheduleAtFixedRate 和 scheduleWithFixedDelay 。它们都可以延时且定期执行任务,但延时的时间是有差别的,下面介绍:
scheduleAtFixedRate ,中文意思为 以固定比率执行,参数有 Runnable command, long initialDelay,long period,TimeUnit unit 第1次执行的时间是initialDelay(unit),第2次执行的时间是initialDelay+period(unit),第3次执行的时间是initialDelay+period*2(unit),依次类推。。。也就是,在任务开始后,period时间后,便会执行下一次任务。如果period时间到了,但上一次还没执行完毕,则等待,直到上一次的任务执行完毕,然后马上执行本次任务。
scheduleWithFixedDelay ,中文意思为 以固定的延迟来执行,参数有 Runnable command, long initialDelay,long delay,TimeUnit unit ,该方法第1次执行也是在initialDelay(unit)后,但第2次执行是在第1次执行完毕后算起的delay时间后再执行。
因此,这两个方法的不同点是,scheduleAtFixedRate 是从任务开始时算起,scheduleWithFixedDelay 是从任务结束时算起。。。
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后
以上就是关于schedule和scheduleAtFixedRate的区别全部的内容,如果了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!