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.
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
Advertisement
Answer
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.