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:
Firstly, we have to create an object of
ExecutorServiceclass.
ExecutorService executor = Executors.newScheduledThreadPool(2);
To assign a task to a thread that executes after a certain delay we use
schedulemethod:
executor.schedule(new Runnable() {@Overridepublic void run() {System.out.println("Job completed after a delay");}}, 5, TimeUnit.SECONDS);
To keep executing a job after a fixed interval we can use
scheduleAtFixedRatemethod:
executor.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("Job completed at a fixed rate");}}, 0, 10, TimeUnit.SECONDS);
Close the
ExecutorServiceto 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() {@Overridepublic void run() {System.out.println("Job completed after a delay");}}, 5, TimeUnit.SECONDS);executor.scheduleAtFixedRate(new Runnable() {@Overridepublic 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
schedulemethod will print the message "Job completed after a delay" after five seconds of delay.Lines 16–21: The
scheduleAtFixedRatemethod 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
shutdownmethod.
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