Suppose I have a task that is pulling elements from a java.util.concurrent.BlockingQueue and processing them.
public void scheduleTask(int delay, TimeUnit timeUnit) { scheduledExecutorService.scheduleWithFixedDelay(new Task(queue), 0, delay, timeUnit); }
How can I schedule / reschedule the task if the frequency can be changed dynamically?
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.
To execute a task in this scheduled executor after a period of time, you have to use the schedule() method. This method receives the following three parameters: The task you want to execute. The period of time you want the task to wait before its execution.
ScheduledThreadPoolExecutor class in Java is a subclass of ThreadPoolExecutor class defined in java. util. concurrent package. As it is clear from its name that this class is useful when we want to schedule tasks to run repeatedly or to run after a given delay for some future time. It creates a fixed-sized Thread Pool.
The newScheduledThreadPool() method of Executors class creates a thread pool that can schedule commands to run after a given delay or to execute periodically.
Use schedule(Callable<V>, long, TimeUnit)
rather than scheduleAtFixedRate
or scheduleWithFixedDelay
. Then ensure that your Callable reschedules itself or a new Callable instance at some point in the future. For example:
// Create Callable instance to schedule. Callable<Void> c = new Callable<Void>() { public Void call() { try { // Do work. } finally { // Reschedule in new Callable, typically with a delay based on the result // of this Callable. In this example the Callable is stateless so we // simply reschedule passing a reference to this. service.schedule(this, 5000L, TimeUnit.MILLISECONDS); } return null; } } service.schedule(c);
This approach avoids the need to shut down and recreate the ScheduledExecutorService
.
I don't think you can change a fixed rate delay. I think you need to use schedule() to perform a one-shot, and schedule again once that has completed (with a modified time out if required).
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