Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ScheduledExecutorService in java to call a Callable implementation at fixed interval?

Tags:

java

ScheduledExecutorService has methods like scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit) to invoke Runnable classes at fixed intervals. I want my Thread to return some value after execution. So I implemented Callable interface. I could not find an equivalent method for invoking my Callable class at regular interval. Is there any other way to implement this? If this is functionality is not provided by Java, what is the rational behind that decision? Please let me know. Thanks.

like image 448
user131476 Avatar asked Feb 24 '11 09:02

user131476


People also ask

What is ScheduledExecutorService in Java?

public interface ScheduledExecutorService extends ExecutorService. An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.

What is the difference between ExecutorService and ScheduledExecutorService?

ScheduledExecutorService is an ExecutorService which can schedule tasks to run after a delay, or to execute repeatedly with a fixed interval of time in between each execution. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService .

How do you run a specific task everyday at a particular time using ScheduledExecutorService?

getSeconds(); ScheduledExecutorService scheduler = Executors. newScheduledThreadPool(1); scheduler. scheduleAtFixedRate(new MyRunnableTask(), initialDelay, TimeUnit. DAYS.


1 Answers

You can't schedule Callable for periodic execution since it's unclear how to return a result from such an execution.

If you have your own approach to returning the result (for example, placing a result into a queue), you can wrap Callable into Runnable and implement your approach:

final BlockingQueue<Result> q = new ArrayBlockingQueue<Result>();
final Callable<Result> action = ...;

s.scheduleAtFixedRate(new Runnable() {
    public void run() {
        q.put(action.call());
    }
}, ...);
like image 137
axtavt Avatar answered Oct 17 '22 06:10

axtavt