如何以有保证的固定速率调度 Java 任务,而不受任务运行时间的影响? [英] How can I schedule Java tasks at guaranteed fixed rate, independent of task run time?

查看:41
本文介绍了如何以有保证的固定速率调度 Java 任务,而不受任务运行时间的影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.Timer 的 scheduleAtFixedRate 是一个明显的替代方案,如果你想在某个时间间隔安排任务.但是,如果您的间隔是 10 秒.并且任务耗时超过 10 秒.根据文档,此函数将忙于执行任何挂起的事情(引用:两个或多个执行将快速连续发生以赶上".).这当然是一种合理的实现方式,但不一定是您想要的.

java.util.Timer's scheduleAtFixedRate is an obvious alternative if one wants to schedule tasks at a certain interval. However, if your interval is 10 s. and the tasks take more than 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.

有谁知道 Java API 中用于在任务 n 之后调度任务 n+1 毫秒的标准功能,与任务 n 花费的时间无关?

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?

我现在自己实现了这个功能两次(两个不同的项目),因为在我偶然发现的情况下,这是实现它的最正确方法.

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.

我在这里的主要观点是,如果追赶"策略被认为是正确的",那么我在这里的方法在很多情况下同样正确,我认为 scheduleAtFixedRate 应该包含一个选项.这对我来说不是问题,我只是想看看是否有人知道这是否已经在 J​​ava API 中实现,所以我不必时不时地编写代码.

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. 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.

推荐答案

经过一些(重新)搜索,我相信 scheduleWithFixedDelay 方法 ScheduledExecutorService 正是实现了这一点.

After some (re)searching, I believe the scheduleWithFixedDelay method of ScheduledExecutorService implements exactly this.

这篇关于如何以有保证的固定速率调度 Java 任务,而不受任务运行时间的影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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