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.
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.
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 .
getSeconds(); ScheduledExecutorService scheduler = Executors. newScheduledThreadPool(1); scheduler. scheduleAtFixedRate(new MyRunnableTask(), initialDelay, TimeUnit. DAYS.
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());
}
}, ...);
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