问题描述
<$ h $ => http:// docs的 scheduleAtFixedRate
和 scheduleWithFixedDelay
方法之间的主要区别是什么? oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html\">ScheduledExecutorService ?
What's the main difference between scheduleAtFixedRate
and scheduleWithFixedDelay
methods of ScheduledExecutorService?
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("scheduleAtFixedRate: " + new Date());
}
}, 1, 3L , SECONDS);
scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("scheduleWithFixedDelay: " + new Date());
}
}, 1, 3L , SECONDS);
它们在同一时间打印完全相同,似乎它们以完全相同的间隔执行。
they print exact the same time, seems they are executed at exact the same interval.
推荐答案
尝试在<$ c中添加 Thread.sleep(1000);
来电$ c> run() method ...基本上,根据前一次执行结束的时间和它(逻辑上)启动时的时间安排。
Try adding a Thread.sleep(1000);
call within your run()
method... Basically it's the difference between scheduling something based on when the previous execution ends and when it (logically) starts.
例如,假设我按照每小时一次的固定费率计划一次报警,每次报警都会我要一杯咖啡,需要10分钟。假设从午夜开始,我有:
For example, suppose I schedule an alarm to go off with a fixed rate of once an hour, and every time it goes off, I have a cup of coffee, which takes 10 minutes. Suppose that starts at midnight, I'd have:
00:00: Start making coffee
00:10: Finish making coffee
01:00: Start making coffee
01:10: Finish making coffee
02:00: Start making coffee
02:10: Finish making coffee
如果我安排一个小时的固定延迟,我会: / p>
If I schedule with a fixed delay of one hour, I'd have:
00:00: Start making coffee
00:10: Finish making coffee
01:10: Start making coffee
01:20: Finish making coffee
02:20: Start making coffee
02:30: Finish making coffee
您想要哪一个取决于您的任务。
Which one you want depends on your task.
这篇关于scheduleAtFixedRate vs scheduleWithFixedDelay的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!