安排定期任务和时钟漂移 [英] Scheduling periodic tasks and clock drift

查看:73
本文介绍了安排定期任务和时钟漂移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想安排一个定期任务,每X小时执行一次.我有一个用Java编写的服务,当时我正在考虑创建一个长时间运行的后台线程,只要该服务启动,它就会一直运行.如何确保我们每X个小时执行一次任务?主机上的时钟漂移是我应该担心的问题吗?我知道,如果CPU努力工作,时钟滴答的频率可能会改变.

I would like to schedule a periodic task which executes every X hours. I have a service which is written in Java and I was thinking of creating a long running background thread that runs forever as long as the service is up. How can I ensure that we are executing the task once every X hours? Is clock drift on my host an issue I should be worried about? I know that frequency of the clock ticks may change if the CPUs are working hard.

我正在考虑在我的spring配置中添加一个bean来启动将定期执行任务的线程.

I was thinking of adding a bean to my spring configuration to spin up the thread which will periodically perform my task.

推荐答案

Java提供了

Java provides a java.util.Timer class that is designed to execute a task on a background thread. One of the modes of operation is "repeated execution at regular intervals". There are fixed-delay and fixed-rate execution methods that can be used, depending on your exact needs.

Java 5添加了 java.util.concurrent.ScheduledThreadPoolExecutor 类比 Timer 更为灵活,但还提供了固定延迟和固定速率执行方法.

Java 5 added a java.util.concurrent.ScheduledThreadPoolExecutor class that is more flexible than Timer, but also offers fixed-delay and fixed-rate execution methods.

如果您需要的时间如此不合适,那么我不确定Java是否是合适的解决方案.您将开始进入实时系统的领域.此时,您可能应该在寻找其他选项.

If you need such precise timing that these aren't suitable, I'm not sure that Java is an appropriate solution. You would be starting to enter the realm of a real-time system. At this point, you should likely be looking for other options.

这篇关于安排定期任务和时钟漂移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆