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 retu开发者_开发技巧rn 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.
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.
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
.
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
:
ses.scheduleAtFixedRate(runnableOf(callabale), initialDelay, delay, unit);
精彩评论