Alex Rivera | Logout

Scheduling a Callable at a fixed rate

Asked 2011-09-07T09:42:47.063
10

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.

Edit
Report

1 Answer

-1

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);
answered 2011-09-10T19:05:59.977

Your Answer