ScheduledThreadPoolExecutor的任务调度的准确性如何 [英] How accurate is the task scheduling of a ScheduledThreadPoolExecutor

查看:78
本文介绍了ScheduledThreadPoolExecutor的任务调度的准确性如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 ScheduledThreadPoolExecutor JavaDoc 并遇到以下情况:

I was reading ScheduledThreadPoolExecutor JavaDoc and came across the following thing:


延迟的任务在启用之前立即执行,但没有任何操作
关于启用后何时生效的实时保证
开始。排定为完全相同执行时间的任务以先进先出(FIFO)提交顺序启用

Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.

所以,如果我写这样的话:

So, if I write something like this:

ScheduledExecutorService ses = Executors.newScheduledThreadPool(4); //uses ScheduledThreadPoolExecutor internally
Callable<Integer> c;
//initialize c
ses.schedule(c, 10, TimeUnit.SECONDS);

是否不能保证在计划后的10秒内开始执行可调用对象?据我所知,该规范允许它甚至在计划后的一个小时内执行(没有任何实时保证,如文档中所述)。

there's no any guarantees that the execution of the callable will start in 10 seconds after the scheduling? As far as I got, the specification allows it to execute even in hour after scheduleing (without any real-time guarantees, as stated in the documentation).

它如何在实践中起作用?我应该排除一些很长的延迟吗?

How does it work in practice? Should I excepct some really long delay?

推荐答案

您的理解是正确的。执行器并没有声称自己是具有任何时序保证的实时系统。唯一可以保证的是,它不会过早运行任务。

Your understanding is correct. The Executor is not claiming to be a real-time system with any sort of timing guarantees. The only thing it will guarantee is that it doesn't run tasks too early.

实际上,训练有素的执行器的时间安排非常准确。根据我的经验,它们通常在计划的时间后10毫秒内开始。只有在执行器缺少适当的资源来运行其工作负载时,您才会看到调度被推迟得很远。因此,这更多是一个调整问题。

In practice, the timing of well-tuned Executors are very accurate. Typically they start within 10ms after the scheduled time from my experience. The only time you will see scheduling get pushed back very far is if your Executor is lacking the appropriate resources to run it's workload. So this is more of a tuning issue.

实际上,如果您给执行器足够的资源来使用,则时间安排将非常准确。

Realistically, if you give your Executor enough resources to work with, the timing will be quite accurate.

不想要执行的某些事情是将调度用作基于比率的计算的一部分。例如,如果您将任务安排为每1秒运行一次,并使用它来计算每秒< somemetric> ,而不考虑该任务实际运行的时间。

Some things that you don't want to do with an Executor is use the scheduling as part of a rate-based calculation. For example, if you schedule a task to run every 1 second and you use that to compute <somemetric> per second without factoring in what time the task is actually running at.

要注意的另一件事是上下文切换的成本。如果您安排多个任务每1ms运行一次,执行器将无法跟上您运行任务切换每个人1ms的时间。

Another thing to be mindful of is the cost of context switching. If you schedule multiple tasks to run every 1ms, the Executor will not be able to keep up with running your task and context switching everyone 1ms.

这篇关于ScheduledThreadPoolExecutor的任务调度的准确性如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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