How to schedule jobs using ExecutorService in Java

An ExecutorService is a framework for asynchronously performing tasks. It allows us to schedule tasks to execute at particular times or after predetermined delays. The following describes how to schedule tasks in Java using the ExecutorService:

  1. Firstly, we have to create an object of ExecutorService class.

ExecutorService executor = Executors.newScheduledThreadPool(2);
  1. To assign a task to a thread that executes after a certain delay we use schedule method:

executor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Job completed after a delay");
}
}, 5, TimeUnit.SECONDS);
  1. To keep executing a job after a fixed interval we can use scheduleAtFixedRate method:

executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Job completed at a fixed rate");
}
}, 0, 10, TimeUnit.SECONDS);
  1. Close the ExecutorService to free up resources:

executor.shutdown();

Working example

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ExecutorServiceExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Job completed after a delay");
}
}, 5, TimeUnit.SECONDS);
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Job completed at a fixed rate");
}
}, 0, 10, TimeUnit.SECONDS);
executor.shutdown();
}
}

Explanation

  • Line 7: Create two threads using newScheduledThreadPool() method.

  • Lines 9–14: The schedule method will print the message "Job completed after a delay" after five seconds of delay.

  • Lines 16–21: The scheduleAtFixedRate method will keep printing the message "Job completed at a fixed rate" after a fixed interval of ten seconds.

  • Line 23: Free up all the resources by calling shutdown method.

Note: The order of the output may vary depending on the system and its load. It’s possible that the “Job completed at a fixed rate” message was printed before the “Job completed after a delay” message in your case.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved