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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With