How to use @Scheduled Annotation in Spring?

Tech Insights

In this post we’ll discuss some simple steps to use Spring’s @Scheduled annotation to schedule tasks which are to be invoked automatically and executed at a specific interval of time.

1) Enable Spring’s task scheduling capability

@SpringBootApplication
@EnableScheduling
public class SpringTaskScheduler {
	public static void main(String[] args) {
		SpringApplication.run(SpringTaskScheduler.class);
	}
}

@EnableScheduling annotation should be added to the Spring Boot application class in order to enable Spring’s scheduled task execution capability.

2) Use the @Scheduled annotation

Each method in your scheduler class defines a task and the @Scheduled annotation defines when each task is executed. Following are different ways to use the @Scheduled annotation:

2.1) Scheduling tasks at a fixed delay


You can use the property fixedDelay if you need to add a specific time delay after the completion of execution of a task. Basically it specifies an interval between the end of last execution and the start of next execution of the task. So fixedDelay must be used when a task is to be invoked only after the completion of its previous execution.

@Scheduled(fixedDelay=5000)
public void executeFixedDelayTask() {
    // code to be executed at a fixed delay
}

With the above code, executeFixedDelayTask() will be invoked only after 5 seconds of completion of its previous execution.

2.2) Scheduling tasks at a fixed rate


The property fixedRate can be used if you need to make the task execution independent. It checks for the successive start times of each task to invoke it again.

@Scheduled(fixedRate=5000)
public void executeFixedRateTask() {
    // code to be executed at a fixed rate
}

Here, executeFixedRateTask() will be invoked after 5 seconds of start time of its previous execution.

However, you should note that the fixedRate property doesn’t make the task execution asynchronous or parallel. The invocation of a task always waits for the completion of its previous execution. Most of the times, this behavior helps to avoid exceptions related to memory but there are times you need to have asynchronous execution of tasks. To run tasks in parallel, you need to add the @EnableAsync annotation to the Spring Boot application class and @Async annotation to the method(s) in your scheduler class. See the following code snippets to understand:

2.2.1) Usage of @EnableAsync annotation

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class SpringTaskScheduler {
	public static void main(String[] args) {
		SpringApplication.run(SpringTaskScheduler.class);
	}
}

2.2.2) Usage of @Async annotation

@Async
@Scheduled(fixedRate=5000)
public void executeFixedRateTaskAsynchronous() {
    // code to be executed at a fixed rate
}

executeFixedRateTaskAsynchronous() will be executed every 5 seconds, even if the previous execution is not completed.

2.3) Scheduling tasks with an initial delay

You can use the property initialDelay to indicate the number of milliseconds to wait before the first execution of the method. Check the following code to understand how initialDelay can be used along with fixedDelay:

@Scheduled(fixedDelay=5000, initialDelay = 1000)
public void executeFixedDelayTaskAfterInitialDelay() {
    // code to be executed at a fixed delay but after an initial delay
}

With the initialDelay property in place, first time execution of the method executeFixedDelayTaskAfterInitialDelay() will occur only after the initialDelay value. Once started after the initial delay, the task will continue to be executed based on the fixedDelay property.

3) Using Cron expressions with @Scheduled to schedule tasks

In some cases we need tasks to be executed in way how a Cron job works. @Scheduled annotation supports the usage of Cron expressions.

@Scheduled(cron="0 30 10 * * ?")
public void executeEveryDayTask() {
    // code to be executed every day at 10.30 AM
}

Here, executeEveryDayTask() will be executed every day at 10.30 AM as per the Cron expression given. To know more about Cron jobs and how the expressions can be set, check this.

Notes:

  1. The value of time specified with each property is in milliseconds.
  2. Cron expressions work on the server’s local time zones by default. To set a different time zone, you can use the attribute “zone” along with “cron” or find the specific location’s timezone in your task method.