如何以固定的速率安排任务的持续时间长于该速率? [英] How to schedule a task at fixed rate with a duration longer than the rate?

查看:102
本文介绍了如何以固定的速率安排任务的持续时间长于该速率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安排一个每秒需要运行约2.25秒的任务,因此我知道3个线程应该足以处理负载.我的代码如下:

I'm trying to schedule a task that requires ~2.25 sec to be run every second.Thus I know 3 threads should be enough to handle the load. My code looks like this:

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);
scheduler.scheduleAtFixedRate(new Streamer(), 0, 1000, TimeUnit.MILLISECONDS);

有趣的是,它的行为类似于ScheduledAtFixedDelay,延迟为0(线程每〜2.25秒完成一次).

interestingly this behaves like scheduledAtFixedDelay with a delay of 0 (threads finish every ~2.25 sec).

我知道,如果线程延迟运行,那么scheduleAtFixedRate可能会延迟.但是不应该给执行者更大的线程池来解决这个问题吗?

I know, that scheduleAtFixedRate can be late if a thread runs late. But shouldn't giving the executor a larger threadpool solve this problem?

我可以通过每3秒对3个执行程序进行编码来轻松地规避此问题,但这会给管理带来不必要的困难.

I could easily circumnvent the problem by coding 3 executors to start every 3 seconds, but that would make administration unnecessarily difficult.

是否有解决此问题的简便方法?

Is there an easier solution to this problem?

推荐答案

您可以使用threadPool和调度程序来实现此效果:

  1. 创建一个fixedThreadPool(或满足您需求的其他线程),假设有4个线程-线程数应基于单个任务执行所消耗的时间以及任务的调度速率,基本上numberOfThreads = avgExecTimeOfSingleTaks *频率+ someMargin;

  1. Create a fixedThreadPool (or other that will fullfill your needs), let say with 4 threads - the number of threads should be based on the time single task consumes to execute and the rate at which the tasks are scheduled, basically numberOfThreads = avgExecTimeOfSingleTaks * frequency + someMargin;

然后创建调度程序线程,该线程每隔一秒钟(或其他期望的时间段)将作业添加到fixedThreadPool队列中,然后任务可以重叠.

then create scheduler thread, that every second (or other desired period) will add a job to the fixedThreadPool queue, then the tasks can overlap.

这种解决问题的方法还具有一些额外的优势:

如果您的任务开始花费的时间超过2.25秒,或者您想以更高的频率执行它们,那么您要做的就是向threadPool添加一些线程,而使用其他答案,则需要重新计算并重新安排一切.因此,此方法为您提供了更清晰,更易于维护的方法.

If your tasks start to take longer than 2.25 sec, or you would like to execute them with greater frequency, then all you have to do is to add some threads to the threadPool, whereas using the other answer, you need to recalculate and reschedule everything. So this approch gives you clearer and easier to maintenance approach.

这篇关于如何以固定的速率安排任务的持续时间长于该速率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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