Spring Boot

Scheduler @Scheduled Annotation Spring Boot

Overview

In this article, we will explore Spring Scheduler how we could use it by @Scheduled annotation in the Spring Boot application. We can use it to configure and schedule tasks.

@Scheduled Annotation Spring Boot

This annotation can be used in a Spring Boot application to schedule any task. But there are some simple rules that we need to follow to annotate a method with @Scheduled are:

  • Scheduler method should be void return type if the method has return then returned value will be ignored.
  • There should not be any parameters in the scheduler method

Next, let’s see how we could use the @Scheduled Annotation in the Spring Boot application.

Enable Scheduling in Spring Boot application

The @EnableScheduling annotation enables support for scheduling tasks and the @Scheduled annotation in Spring Boot as below in Java-based configuration:

@Configuration
@EnableScheduling
public class SchedulerConfig {
    ...
}

Let’s move to use @Scheduled Annotation in the Spring Boot application.

Using @Scheduled Annotation in Spring Boot

We can use this annotation @Scheduled in Spring Boot with several defined attributes based on the requirements.

Schedule a Task at Fixed Delay

Let’s start by configuring a task to run after a fixed delay:

@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {

    //Scheduled work here

}

In the above code, the fixedDelay attribute has a duration (1000 milliseconds). This duration is fixed as the end of the last execution and the start of the next execution. In this case, the task always waits until the previous one is finished. This option is better when you want that the previous execution is completed before running again.

Let’s explore another way of configuring a task to run with a fixed rate:

Schedule a Task at a Fixed Rate

Let’s now execute a task at a fixed interval of time:

@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {

    //Scheduled work here

}

In this case, the scheduled task will start running again after crossing the fixed-rate value of duration (1000 milliseconds). This option is good for the execution of the task independently. But note here, scheduled tasks don’t run in parallel by default. If you want to make parallel then you have to add the @Async annotation as below:

@EnableAsync
public class ScheduledFixedRateExample {

    @Async
    @Scheduled(fixedRate = 1000)
    public void scheduleFixedRateTaskAsync() throws InterruptedException {
         
         //Scheduled work here

    }

}

Now this asynchronous task will be invoked each second, even if the previous task isn’t done.

The fixedDelay vs fixedRate

There are the following key differences between the fixedDelay and fixedRate attributes of @Scheduled annotation in Spring Boot.

  • The fixedDelay property makes sure 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.
  • The fixedRate property runs the scheduled task at every n millisecond. It doesn’t check for any previous executions of the task.

Schedule a Task With Initial Delay

Next, let’s schedule a task with a delay:

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void scheduleFixedRateWithInitialDelayTask() {
 
    //Scheduled work here

}

Note how we’re using both fixedDelay as well as initialDelay in this example. The task will be executed the first time after the initialDelay value, and it will continue to be executed according to the fixedDelay.

Schedule a Task Using Cron Expressions

Sometimes we want to schedule a task for a particular time of every day or every month etc. In this case, delays and rates are not enough. Spring provide support to use cron expression to control the schedule of our tasks:

@Scheduled(cron = "0 45 23 * * *")
public void scheduleTaskUsingCronExpression() {
 
    //Scheduled work here
}

In this example, we are scheduling a task to be executed at 11:45 PM every day.

Conclusion

In this article, we explored Spring scheduler using the @Scheduled annotation in the Spring Boot application. It is a simple way to configure and schedule a task that you want to run as per your need automatically.

Previous
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Configure Multiple Databases Spring JPA Spring Boot

Overview In this article, we will explore a simple Spring Boot application to implement a…

3 years ago