[英]Scheduling a Callable at a fixed rate
I have a task that I want to run at a fixed rate.我有一个要以固定速率运行的任务。 However I also need the result of the task after each execution.但是,每次执行后我还需要任务的结果。 Here is what I tried:这是我尝试过的:
The task任务
class ScheduledWork implements Callable<String>
{
public String call()
{
//do the task and return the result as a String
}
}
No I tried to use the ScheduledExecutorService
to scheduled it.不,我尝试使用ScheduledExecutorService
来安排它。 Turns out you cannot schedule a Callable
at a fixed rate, only a Runnable
can be done so.事实证明,您不能以固定速率安排Callable
,只有Runnable
可以这样做。
Please advise.请指教。
Use a producer/consumer pattern : Have the Runnable put its result on a BlockingQueue .使用生产者/消费者模式:让 Runnable 将其结果放在BlockingQueue 上。 Have another thread take() from the queue.从队列中获取另一个线程take() 。
Take is a blocking call (ie only returns when something is on the queue), so you'll get your results as soon as they're available. Take 是一个阻塞调用(即只有在队列中有东西时才返回),所以你会在结果可用时立即得到结果。
You could combine this with the hollywood pattern to provide the waiting thread with a callback so your code gets called when something is available.您可以将其与好莱坞模式相结合,为等待线程提供回调,以便在有可用内容时调用您的代码。
Unless if you don't care about the return value of your Callable
, you can wrap it in a Runnable
and use that to pass to ScheduledExecutorService
.除非您不关心Callable
的返回值,否则您可以将其包装在Runnable
并使用它传递给ScheduledExecutorService
。
public static Runnable runnableOf(final Callable<?> callable)
{
return new Runnable()
{
public void run()
{
try
{
callable.call();
}
catch (Exception e)
{
}
}
};
}
Then when you want to submit to ScheduledExecutroService
you can pass your Callable
:然后当你想提交给ScheduledExecutroService
你可以传递你的Callable
:
ses.scheduleAtFixedRate(runnableOf(callabale), initialDelay, delay, unit);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.