java - 在 Java 中准确调度任务运行

标签 java timer scheduled-tasks

我在安排任务每分钟在我的代码中运行时遇到一些问题。

我尝试了很多方法来做到这一点,例如:

Timer timer = new Timer();

timer.schedule( new TimerTask() {
    public void run() {
       printTime();
    }
 }, 0, 60*1000);

还有:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
    printTime();
};
executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.MINUTES);

这些都打印出不稳定的时间,甚至与我提供的时间都不接近:

2019-12-03T12:48:23.300
2019-12-03T12:48:24.700
2019-12-03T12:48:41.895
2019-12-03T12:48:42.799
2019-12-03T12:48:47.189
2019-12-03T12:48:47.211
2019-12-03T12:48:47.278

这些是我得到的时间,完全错误,有些就在几秒钟之内!当我的代码执行其他任务时,是否有一种准确的方法可以安排任务每分钟运行一次?

我的计划是计算任务触发之间的时间,但 Timer 和 ScheduledExecutor 似乎等待的时间比提供的时间长,而且不仅短。所以这意味着它也将关闭。

最佳答案

我运行下面的代码,它按预期工作

public class Test {
    public static void main(String[] args)  {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        Runnable task = () -> printTime();
        executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.MINUTES);
    }

    private static void printTime() {
        System.out.println(new Date());
    }
}

输出是:

Tue Dec 03 16:06:31 EET 2019
Tue Dec 03 16:07:31 EET 2019
Tue Dec 03 16:08:31 EET 2019
Tue Dec 03 16:09:31 EET 2019

您可能正在运行 TimerTask 的多个实例。您可以将代码提取到实用程序类中,以确保您只有一个实例。

    public enum  PrintTimer {
        INSTANCE;

        private boolean running = false;

        private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        public synchronized void start()  {
            if (!running) {
                running = true;
                Runnable task = () -> printTime();
                executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.MINUTES);
            }
        }

        private static void printTime() {
            System.out.println(LocalDateTime.now());
        }
    }

你可以这样调用它:

PrintTimer.INSTANCE.start();

关于java - 在 Java 中准确调度任务运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59157720/

相关文章:

java - 在字符间隔上附加文本

ios - 如何在swift中实现优化的多个计时器?

spring - 为什么 spring @schedule 不能与 @Lazy 一起使用

java - 从 Java 调用 Python 模块

java - 在Java中解析图像,针对不同的像素颜色使用不同的操作

java - 当 mvn install 神秘失败时 -

Python 的 sleep() CPU 使用率

C++ 简单定时器/滴答函数

c# - 使用 C# 的任务计划程序(计划 .bat(批处理)文件)

c# - .NET 应用程序的最佳调度程序?