以固定速率安排 Callable
我有一个任务想要以固定速率运行。但是我还需要每次执行后任务的结果。这是我尝试过的:
任务
class ScheduledWork implements Callable<String>
{
public String call()
{
//do the task and return the result as a String
}
}
否 我尝试使用 ScheduledExecutorService
来安排它。事实证明,您无法以固定速率安排 Callable
,只有 Runnable
可以这样做。
请指教。
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. Turns out you cannot schedule a Callable
at a fixed rate, only a Runnable
can be done so.
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用生产者/消费者模式:拥有可运行将其结果放在 BlockingQueue。有另一个线程 take( ) 从队列中。
Take 是一个阻塞调用(即仅当队列中有内容时才返回),因此您将在结果可用时立即获得结果。
您可以将其与 好莱坞模式 结合起来,为等待线程提供回调,以便您的代码被调用当有东西可用时。
Use a producer/consumer pattern: Have the Runnable put its result on a BlockingQueue. Have another thread take() from the queue.
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.
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.
除非您不关心
Callable
的返回值,否则您可以将其包装在Runnable
中,并使用它传递给ScheduledExecutorService
。然后,当您想要提交到
ScheduledExecutroService
时,您可以传递您的Callable
:Unless if you don't care about the return value of your
Callable
, you can wrap it in aRunnable
and use that to pass toScheduledExecutorService
.Then when you want to submit to
ScheduledExecutroService
you can pass yourCallable
: