Periodically execute a task in Java
This post will discuss how to schedule a task for repeated execution in a Java application.
1. Using ScheduledExecutorService
ScheduledExecutorService is an ExecutorService that can schedule commands to run after a given delay, or to execute periodically. 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.
Here’s a class with a method that sets up a ScheduledExecutorService to run the method run every second (in Java 8 and above):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; class Main { private static void run() { System.out.println("Running: " + new java.util.Date()); } public static void main(String[] args) { ScheduledExecutorService executorService; executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleAtFixedRate(Main::run, 0, 1, TimeUnit.SECONDS); } } |
2. Using Timer Class
Timer class provides facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. The schedule() and scheduleAtFixedRate() methods schedules the specified task for repeated fixed-delay execution and fixed-rate execution, respectively. These methods are overloaded.
The following code uses the Timer class to run the method run every second (in Java 8 and above):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Timer; import java.util.TimerTask; class Main { public static void main(String[] args) throws InterruptedException { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("Running: " + new java.util.Date()); } }, 0, 1000); } } |
3. Using Guava Library
Another plausible way of scheduling is to use Guava’s AbstractScheduledService class to perform some periodic tasks while running. Subclasses implement runOneIteration() to specify one iteration of the task, as well as the familiar startUp() and shutDown() methods.
To describe the execution schedule, you must implement the scheduler() method. Typically, you will use one of the provided schedules from AbstractScheduledService.Scheduler, either newFixedRateSchedule() or newFixedDelaySchedule(), corresponding to the familiar methods in ScheduledExecutorService.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import com.google.common.util.concurrent.AbstractScheduledService; import java.util.Date; import java.util.concurrent.TimeUnit; class ScheduledExecutor extends AbstractScheduledService { @Override protected void startUp() { System.out.println("Job started at: " + new java.util.Date()); } @Override protected void runOneIteration() throws Exception { System.out.println("Running: " + new java.util.Date()); } @Override protected Scheduler scheduler() { // execute every second return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS); } @Override protected void shutDown() { System.out.println("Job terminated at: " + new java.util.Date()); } } class Main { public static void main(String[] args) throws InterruptedException { ScheduledExecutor executor = new ScheduledExecutor(); executor.startAsync(); Thread.sleep(10000); executor.stopAsync(); } } |
4. Using Quartz Scheduler
We can also use the Quartz job scheduling library, which can be integrated within virtually any Java application. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs, jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do.
5. With Spring Framework
The Spring Framework provides abstractions for the asynchronous execution and scheduling of tasks with the TaskExecutor and TaskScheduler interfaces. Read more about Spring task execution and scheduling here.
That’s all about periodically executing a task in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)