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):

Download Code

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):

Download Code

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.

Download Code

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.