java - scheduleAtFixedRate 与 scheduleWithFixedDelay

标签 java scheduled-tasks scheduledexecutorservice

ScheduledExecutorServicescheduleAtFixedRatescheduleWithFixedDelay 方法的主要区别是什么? ?

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);

它们在完全相同的时间打印,似乎它们以完全相同的间隔执行。

最佳答案

尝试在您的 run() 方法中添加 Thread.sleep(1000); 调用...基本上,这是根据上次执行时间安排某事之间的区别结束以及何时(逻辑上)开始

例如,假设我安排一个闹钟以每小时一次的固定频率响起,每次响起时,我都会喝一杯咖啡,这需要 10 分钟。假设从午夜开始,我会:

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

如果我安排一个固定的延迟一小时,我会:

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

你想要哪一个取决于你的任务。

关于java - scheduleAtFixedRate 与 scheduleWithFixedDelay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649842/

相关文章:

java - 正则表达式匹配并替换字符串之间的两个字符

java - 如何防止 Spring Boot Batch 应用程序在执行测试时运行?

c# - 任务计划程序定期停止运行 C# 控制台应用程序

java - Java 中 ScheduledExecutorService 的时间一致性问题

java - 我们可以将消息写入Java Web应用程序中的不同响应对象吗?

Java InputMismatchException 与 Scanner 循环

google-bigquery - 计划从 Google BigQuery 导出到 Google Cloud Storage

c# - Microsoft.Win32.TaskScheduler 随机延迟

java - 我如何创建一个每 0.1 秒运行一次并且可以向其中传递一个数组的可执行文件

java - executor.shutdown()的使用