Java ScheduledExecutorService with Examples

Learn to execute a task after a period of time or execute it periodically using ScheduledExecutorService class in Java using ScheduledThreadPoolExecutor.

1. ScheduledExecutorService Interface

By default, Executor framework provides the ThreadPoolExecutor class to execute Callable and Runnable tasks with a pool of threads, which helps us avoid all thread creation boiler-plate code. When we send a task to the executor, it’s executed as soon as possible, according to the configuration of the executor.

But when we are not interested in executing a task as soon as possible and want to execute a task after a period of time or do it periodically, we can use ScheduledExecutorService interface along with its implementation, namely the ScheduledThreadPoolExecutor class.

public interface ScheduledExecutorService extends ExecutorService 
{
  public ScheduledFuture<?> schedule(Runnable command,
          long delay, TimeUnit unit);
 
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
          long delay, TimeUnit unit);
 
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
        long initialDelay,
        long period,
        TimeUnit unit);
 
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
            long initialDelay,
          long delay,
          TimeUnit unit);
}
  • The schedule() methods create tasks with various delays and return a task object that can be used to cancel or check execution.
  • The scheduleAtFixedRate() and scheduleWithFixedDelay() methods create and execute tasks that run periodically until cancelled.
  • Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.
  • All schedule methods accept relative delays and periods as arguments, not absolute times or dates.
  • To schedule at a certain future date, we can use the api in following manner – schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS).
  • All methods return the ScheduledFuture object which is a delayed result-bearing action that can be cancelled.

2. ScheduledExecutorService Examples

In this example, we will execute a simple task under various scenarios to better understand the usage of this interface.

class Task implements Callable<String> {
  private final String name;

  public Task(String name) {
    this.name = name;
  }

  @Override
  public String call() throws Exception {
    return "Task [" + name + "] executed on : " + LocalDateTime.now().toString();
  }
}

2.1. Execute a Single Execution after a Delay

In the following example, we are executing a task after 10 seconds. The task will be executed only once. The executor will be shut down so it can’t accept anymore tasks. The executor will wait for 1-hour maximum for the task to be complete. If the task is not completed in 1 hour, it will be killed forcefully.

public class ScheduledExecutorServiceExample {

  public static void main(String[] args) throws InterruptedException, ExecutionException {

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    System.out.println("Task scheduled to execute after 10 seconds at : " + LocalDateTime.now().toString());

    Task task = new Task("App-Task");
    ScheduledFuture<?> result = executor.schedule(task, 10, TimeUnit.SECONDS);

    System.out.println("Shutdown and await requested at : " + LocalDateTime.now().toString());
    shutdownAndAwaitTermination(executor);
  }

  static void shutdownAndAwaitTermination(ExecutorService executorService) {
    executorService.shutdown();
    try {
      if (!executorService.awaitTermination(1, TimeUnit.HOURS)) {
        executorService.shutdownNow();
      }
    } catch (InterruptedException ie) {
      executorService.shutdownNow();
      Thread.currentThread().interrupt();
    }
  }
}

Program output.

Task scheduled to execute after 10 seconds at : 2022-08-07T15:29:28.347677800
Shutdown and await requested at : 2022-08-07T15:29:28.347677800
Task [App-Task] executed on : 2022-08-07T15:29:38.365194500

2.2. Execute a Task Periodically

If we want to execute a task at a given time, we can use the methods scheduleWithFixedDelay() or scheduleWithFixedRate(). They will continue running the tasks until cancelled or interrupted.

When we use the scheduleWithFixedDelay() method, there is a guaranteed time difference between two executions of the task. The second execution will start only after the given delay time since the first execution ends.

So in the following example, if the task takes 5 seconds to complete and the first execution started on 1:00:00 AM then the second execution will start at 1:00:15 AM.

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

Task task = new Task("App-Task");
ScheduledFuture<?> result = executor1.scheduleWithFixedDelay(task1, 0, 10, TimeUnit.SECONDS);

Program output if the task takes 5 seconds to complete.

Task [App-Task] executed on : 2022-08-07T15:33:40.853289200
Task [App-Task] executed on : 2022-08-07T15:33:55.868004500
...
...

When we use scheduleWithFixedRate() method then task execution start at the fixed delay period. It does not consider if the previous task is still running or not.

In the following example, each task execution will start after 10 seconds. It will not wait for the previous execution to complete.

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

Task task = new Task("App-Task");
ScheduledFuture<?> result = executor1.scheduleWithFixedRate(task1, 0, 10, TimeUnit.SECONDS);

Program output if the task takes 5 seconds to complete.

Task [App-Task] executed on : 2022-08-07T15:33:40.853289200
Task [App-Task] executed on : 2022-08-07T15:33:50.868004500
Task [App-Task] executed on : 2022-08-07T15:33:60.868007502
...
...

Drop me your questions related to ScheduledExecutorService in the comments.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial