How to Schedule Tasks with Spring Boot

Rasalingam Ragul
4 min readFeb 5, 2023

--

In this article, You’ll learn how to schedule tasks in Spring Boot using @Scheduled annotation. You’ll also learn how to use a custom thread pool for executing all the scheduled tasks.

The @Scheduled annotation is added to a method along with some information about when to execute it, and Spring Boot takes care of the rest. Spring Boot internally uses the TaskScheduler interface for scheduling the annotated methods for execution.

The purpose of this article is to build a simple project demonstrating all the concepts related to task scheduling.

Creating the Spring Boot Application for Scheduling

To work with some examples, let us first create a Spring Boot project with the help of the Spring boot Initializr, and then open the project in our favorite IDE. We have not added any dependencies to Maven pom.xml since the scheduler is part of the core module of the Spring framework.

Enabling Scheduling

Scheduling is not enabled by default. Before adding any scheduled jobs we need to enable scheduling explicitly by adding the @enableScheduling annotation:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class JobschedulingApplication {

public static void main(String[] args) {
SpringApplication.run(JobschedulingApplication.class, args);
}

}

Enabling Scheduling Based on a Property

We would also like to disable scheduling during running tests. For this, we need to add a condition to our SchedulerConfig class. Let us add the @ConditionalOnProperty annotation with the name of the property we want to use to control the schedule:

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
@ConditionalOnProperty(name = "scheduler.enabled", matchIfMissing = true)
public class SchedulerConfig {

}

Here we have specified the property name as scheduler.enabled. We want to enable it by default. For this, we have also set the value of matchIfMissing to true which means we do not have to set this property to enable scheduling but have to set this property to explicitly disable the scheduler.

Adding Scheduled Jobs

After enabling scheduling, we will add jobs to our application for scheduling. We can turn any method into a Spring bean for scheduling by adding the @Scheduled annotation to it.

The @Scheduled is a method-level annotation applied at runtime to mark the method to be scheduled. It takes one attribute from cron, fixedDelay, or fixedRate for specifying the schedule of execution in different formats.

The annotated method needs to fulfill two conditions:

  1. The method should not have a return type and so return void. For methods that have a return type, the returned value is ignored when invoked through the scheduler.
  2. The method should not accept any input parameters.

In the next sections, we will examine different options for configuring the scheduler to trigger the scheduled jobs.

Schedule a Task at a Fixed Delay

In this case, the duration between the end of the last execution and the start of the next execution is fixed. The task always waits until the previous one is finished.

@Scheduled(fixedDelay = 10000)
public void run() {
System.out.println("Current time is :: " + Calendar.getInstance().getTime());
}

Schedule a Task at a Fixed Rate

In this use case, each execution of the task is independent.

Here, the scheduled tasks don’t run in parallel by default. So even if we used fixedRate, the next task won’t be invoked until the previous one is done.

@Scheduled(initialDelay = 1000, fixedRate = 10000)
public void run() {
System.out.println("Current time is :: " + Calendar.getInstance().getTime());
}

When to Use Which?

We can run a scheduled task using Spring’s @Scheduled annotation. However, based on the properties fixedDelay and fixedRate, the nature of execution changes.

The fixedDelay property ensures that there is a delay of n millisecond between the finish time of an execution of a task and the start time of the next execution of the task. For dependent jobs, it is quite helpful.

The fixedRate property runs the scheduled task at every n millisecond. It doesn’t check for any previous executions of the task. This is useful when all executions of the task are independent.

Schedule a Task using Cron Expressions

A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule. These fields, separated by white space, can contain any of the allowed values with various combinations of the allowed characters for that field.

Sometimes delays and rates are not enough, and we need the flexibility of a cron expression to control the schedule of our tasks.

Let us take an example of scheduling a task that is to be executed at 10 AM on the 10th day of every month.

@Scheduled(cron = "0 10 10 10 * ?")
public void scheduleTask() {
System.out.println("Current time is :: " + Calendar.getInstance().getTime());
}

Conclusion

In this article, you learned how to schedule tasks in Spring Boot using @Scheduled annotation.

--

--