简体   繁体   English

如何以保证的固定速率调度Java任务,而与任务运行时间无关?

[英]How can I schedule Java tasks at guaranteed fixed rate, independent of task run time?

java.util.Timer's scheduleAtFixedRate is an obvious alternative if one wants to schedule tasks at a certain interval. 如果要按特定的时间间隔计划任务,则java.util.Timer的scheduleAtFixedRate是一种明显的选择。 However, if your interval is 10 s. 但是,如果您的间隔是10 s。 and the tasks take more than 10 s. 并且任务耗时超过10 s。 this function will busy-execute anything pending according to the documentation (quote: two or more executions will occur in rapid succession to "catch up."). 该功能将根据文档忙于执行任何未决的操作(引用:两个或更多个执行将快速连续进行以“追赶”。) This is of course a reasonable way to implement it, but it's not necessarily what you want. 这当然是实现它的一种合理方法,但不一定是您想要的。

Does anyone know about standard functionality in the Java API for scheduling task n+1 <interval> milliseconds after task n, independent of how long time task n took? 是否有人知道Java API中用于在任务n之后调度任务n + 1 <interval>毫秒的标准功能,而与任务n花费了多长时间无关?

I've implemented this functionality myself twice now (two different projects) because it's simply the most correct way to implement it in the cases I've stumbled upon. 我现在已经两次实现了该功能(两个不同的项目),因为在我偶然遇到的情况下,这只是实现它的最正确方法。

You might say this is trivial (and it is) but I hadn't mentioned it if it wasn't a recurring thing. 您可能会说这是微不足道的(但确实如此),但如果不是重复出现的话,我没有提到。

My main point here is that if the "catching up" strategy is deemed "correct", then my approach here would be equally correct in quite a few cases and I think scheduleAtFixedRate should include an option for it. 我的主要观点是,如果将“追赶”策略视为“正确”,那么在很多情况下,我的方法同样正确,我认为scheduleAtFixedRate应该包括一个选项。 This isn't a problem for me, I just wanted to see if anyone knew if this was implemented already in the Java API so I don't have to code it now and then. 这对我来说不是问题,我只是想看看是否有人知道它是否已经在Java API中实现,所以我不必时不时地编写代码。

This would be accomplished with the schedule() methods (assuming java.util.Timer is being used). 这可以通过schedule()方法来完成(假设正在使用java.util.Timer )。 It provides fixed delay as opposed to fixed rate. 它提供固定的延迟而不是固定的速率。

经过一些(重新)搜索后,我相信ScheduledExecutorServicescheduleWithFixedDelay方法正是实现了这一点。

I think this does exactly what you want. 我认为这正是您想要的。 Java.util.timer -> schedule(TimerTask task, long delay, long period). Java.util.timer->调度(TimerTask任务,延迟长,周期长)。 This executes with "fixed delay". 这以“固定延迟”执行。 According to the documentation: 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. 如果执行由于任何原因(例如垃圾回收或其他后台活动)而延迟,则后续执行也将延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM