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 ExecutorService
class.
ExecutorService executor = Executors.newScheduledThreadPool(2);
To assign a task to a thread that executes after a certain delay we use schedule
method:
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 scheduleAtFixedRate
method:
executor.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("Job completed at a fixed rate");}}, 0, 10, TimeUnit.SECONDS);
Close the ExecutorService
to free up resources:
executor.shutdown();
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();}}
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