ScheduledExecutorService.scheduleAtFixedRate()方法如何保证实时执行?

发布于 2024-08-06 02:19:31 字数 248 浏览 8 评论 0原文

因为我每秒都在执行一项时间关键的任务,所以我比较了几种方法来找到确保我的任务真正以固定时间步执行的最佳方法。在计算了所有方法的错误的标准导数之后,似乎使用方法 scheduledExecutorService.scheduleAtFixedRate() 会得到最好的结果,但我不知道为什么会这样。

有谁知道该方法内部是如何工作的?例如,与简单的 sleep() 相比,它如何确保引用的任务真正以固定的时间步长执行?

Because I'm executing a time critical task every second, I compared several methods to find the best way to ensure that my task is really executed in fixed time steps. After calculating the standard derivation of the error for all methods it seems like using the method scheduledExecutorService.scheduleAtFixedRate() leads to the best results, but I don't have a clue why it is so.

Does anybody know how that method internally works? How does it for example in comparison to a simple sleep() ensure that the referenced task is really executed in fixed time steps?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷心人i 2024-08-13 02:19:31

“普通”Java VM 无法对执行时间做出任何硬实时保证(因此也无法保证调度时间)。如果您确实需要硬实时保证,您应该看看实时虚拟机,例如 Java RTS。当然,在这种情况下您也需要一个实时操作系统。

关于与 Thread.sleep() 的比较:与 Thread.sleep() 的(天真的)用法相比,scheduledExecutorService.scheduleAtFixedRate() 的优点是它不受计划任务的执行时间的影响。请参阅 ScheduledFutureTask.runPeriodic() 了解其实现方式。

A 'normal' Java VM cannot make any hard real-time guarantees about execution times (and as a consequence of that also about scheduling times). If you really need hard real time guarantees you should have a look at a real time VM like Java RTS. Of course you need a real time OS in that case too.

Regarding comparison to Thread.sleep(): the advantage of scheduledExecutorService.scheduleAtFixedRate() compared to a (naive) usage of Thread.sleep() is that it isn't affected by the execution time of the scheduled task. See ScheduledFutureTask.runPeriodic() on how this is implemented.

伊面 2024-08-13 02:19:31

您可以查看 ScheduledThreadPoolExecutor 的 OpenJDK7 实现。 java 这是唯一实现 ScheduledExecutorService 接口的类。

但据我所知 ScheduledExecutorService 中有关于准确性的保证。因此,即使您的测量结果表明这是准确的,但如果您切换到不同的平台、 vm 或 jdk ,情况可能并非如此。

You can have a look of the OpenJDK7 implementation of ScheduledThreadPoolExecutor.java which is the only class implementing the ScheduledExecutorService interface.

However as far as I know there is guarantee in the ScheduledExecutorService about accuracy. So even if your measurments show this to be acurate that may not be the case if you switch to a different platform, vm or jdk .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文