Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ScheduledExecutorService not executing task with an initialDelay 0

ScheduledExecutorService not executing a submitted task with an initialDelay of 0 time units when using scheduleWithFixedDelay or scheduleAtFixedRate. But it is executing the task when i call schedule on it

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> System.out.println("I am a runnable");
scheduledExecutorService.schedule(runnable, 0, TimeUnit.SECONDS);
scheduledExecutorService.shutdown();

Output

I am a runnable

But when I use scheduleWithFixedDelay or scheduleAtFixedRate instead of schedule the task is not getting executed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> System.out.println("I am a runnable");
scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 1, TimeUnit.SECONDS);
// or  scheduledExecutorService.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
scheduledExecutorService.shutdown();

Why is the task not getting executed in this scenario? I expected this task to be executed as the initialDelay is set to 0

>Solution :

Your call to ExecutorService#shutdown stops any further scheduling of tasks. Apparently your call happens so quickly that the scheduler never got to execute the first run of the scheduled task. This makes sense.

What does not quite make sense is why a call to schedule happens to get scheduled fast enough to get its task executed in time before the shutdown, but calls to scheduleWithFixedDelay or scheduleAtFixedRate with a delay of zero do not get scheduled as quickly. Apparently there is some overhead in the scheduleWithFixedDelay and scheduleAtFixedRate calls, enough overhead that the program exits before they get a chance to make their first executions.

Anyways, you can see the behavior in my version of your code running live at IdeOne.com. Adding this line:

Thread.sleep( 1_000 * 5 ) ;

… before your shutdown gives enough time for some of the scheduleWithFixedDelay and scheduleAtFixedRate tasks to execute.

Or see the same effect by adding a call to awaitTermination as shown in correct Answer by Nguyen.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading