Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Turns out you cannot schedule a Callable at a fixed rate, only a Runnable can be done so.

Please advise.

like image 425
user801138 Avatar asked Sep 07 '11 09:09

user801138


1 Answers

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.

like image 127
Bohemian Avatar answered Sep 20 '22 13:09

Bohemian