Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute all pending scheduled tasks from a ScheduledExecutorService in Java

Tags:

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.

like image 769
Carlos Andres Avatar asked May 09 '20 21:05

Carlos Andres


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.


2 Answers

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.

  • If you care about the tasks running serially, and not overlapping their executions in time, then use a single-threaded executor service.
    • ExecutorService es = Executors.newSingleThreadExecutor​() ;
  • If, instead, you care about getting a bunch of tasks done as soon as possible, then you might want to use an executor service backed by a thread pool. This assumes your deployment machine has multiple cores, and/or your your tasks are not CPU-bound (the tasks spend significant time waiting on resources such as network calls, reading/writing to storage drives, database queries, etc.).
    • 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.

like image 140
Basil Bourque Avatar answered Sep 28 '22 08:09

Basil Bourque


ExecutorService::shutdownNow

The object ScheduledExecutorService has a method: shutdownNow(). It will return a List<Runnable> that can be executed.

like image 30
Carlos Andres Avatar answered Sep 28 '22 07:09

Carlos Andres