I'm using ScheduledExecutorService for requeuing events back into a message queue after sometime has passed. Now I need that after some event is triggered all the scheduled pending tasks of this executor are executed.
I have seen that it is possible to cancel the pending tasks, but I need to run all of them before the executor is closed. Is there a way to do this? Or should I use a different strategy to schedule this tasks.
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.
Or should I use a different strategy to schedule this tasks.
Yes, you should use another strategy.
As the same suggests, a ScheduledExecutorService
is for scheduling to run a task after a certain amount of time has passed. If you do not know when a task
If you want to buffer some tasks to be executed at a later undetermined time, collect your Runnable
or Callable
objects as you would any other bunch of objects. Use a class from the Java Collections framework.
If you care about the tasks being run in a particular order, such as LIFO or FIFO, use a Queue
or Deque
implementation.
When the time arrives to run your tasks, feed the Runnable
/Callable
objects from the queue/deque and submit to an executor service.
ExecutorService es = Executors.newSingleThreadExecutor() ;
ExecutorService es = Executors.newCachedThreadPool() ;
ExecutorService es = Executors.newFixedThreadPool( 4 ) ;
Obligatory tip: Read, re-read, and study the superb book, Java Concurrency in Practice by Brian Goetz, et al.
ExecutorService::shutdownNow
The object ScheduledExecutorService
has a method: shutdownNow()
.
It will return a List<Runnable>
that can be executed.
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