You are here
Home > java >

Annotation @Scheduled Spring Boot Scheduler With Examples

Spring Scheduling Annotations @Scheduled Spring BootIn this article, we will discuss on โ€˜@Scheduled Spring Boot Scheduling Annotationsโ€™ with examples. Needless to say, Scheduling is an important part of a production grade application. Hence, learning of Spring Scheduling Annotations also becomes equally important. These annotations play a crucial role in creating an application in Spring Boot. If you want to learn all annotations which are generally used in a Spring Boot Project, kindly visit our article โ€˜Spring Boot Annotations with Examplesโ€˜. Letโ€™s discuss about @Scheduled Spring Boot Scheduling Annotations and other annotations in detail with examples here only.

Since scheduling is part of Spring Core, we donโ€™t need to add any specific dependency to get the features of it. Moreover, all the annotations of Spring Scheduling will also apply to Spring Boot Application. In order to have complete understanding on Scheduling in Spring Boot, you may visit Spring Boot Scheduler article.

@EnableScheduling

Since scheduling is not enabled by default, we need to enable scheduling explicitly by adding the @EnableScheduling annotation before implementing any scheduled jobs. In order to enable Scheduling in our application, we need to apply @EnableScheduling in conjunction with @Configuration. We can also use it on our main class as it has @Configuration enabled by default. For example, below code demonstrates the use of annotation.

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

Please note that if you are using this annotation in your main class(having annotation @SpringBootApplication) of application, you donโ€™t need to apply @Configuration, as it is already available with@SpringBootApplication. Below code snippet illustrates the concept:

@EnableScheduling  
@SpringBootApplication
public class SpringBootSchedulingApplication {

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

@Scheduled

This is a method level annotation. If we want a method to execute periodically, we can annotate that method with @Scheduled. This annotation instructs Spring Container to execute the method in a loop as per the provided parameters until the application/server stops.

The method annotated with @Scheduled should not return any value, ie. It should have a void return type and even it should not have any parameter. Furthermore, it uses below concepts to support scheduling.

1) fixed Delay
2) fixed Rate
3) cron expression

@Scheduled can take one attribute from cron, fixedDelay, or fixedRate to figure out the schedule of execution in various formats.

โ™ฆ Note: You canโ€™t write @Scheduled without providing any input as an attribute of it, otherwise Spring container will throw IllegalStateException: Encountered invalid @Scheduled method โ€˜XYZ()โ€™: Exactly one of the โ€˜cronโ€™, โ€˜fixedDelay(String)โ€™, or โ€˜fixedRate(String)โ€™ attributes is required.

@Scheduled with fixedDelay

A fixed delay represents the interval between the end of the previous job and the beginning of the new job.

@Scheduled(fixedDelay = 4000)
  // @Scheduled(fixedDelayString = "4000")              
public void scheduledMethod() {
     System.out.println(" Scheduler with Fixed delay :" + new Date());
}

In case of fixedDelay, there is a delay of 4000 milliseconds(4 seconds) between the finish time of an execution of a task and the start time of the next execution of the task.

โ™ฅ Note:ย  We can provide fixedDelay input in two ways : Integer and String (For example, look at the above code example)
Integer type : @Scheduled(fixedDelay = 4000)
String type : @Scheduled(fixedDelayString = โ€œ4000โ€)

String value input also offers us to externalize the configuration by using Spring Expressions and storing them in properties files as shown in the example below:

@Scheduled(fixedDelayString = "${fixedDelay.input}")
@Scheduled(cron = "${cron.expression}")

Apart from that we can also utilize fixedDelayString and fixedRateString by specifying the time interval in the ISO duration format. We will discuss some of the examples in below sections.

@Scheduled withย fixedDelay & initialDelay

We can opt to delay the first execution of the method by specifying the interval using the initialDelay attribute. The task will execute for the first time after the initialDelay value, and it will continue executing as per the fixedDelay.

@Scheduled(initialDelay = 5000, fixedDelay = 9000)
 // @Scheduled(initialDelayString = "5000" ,fixedDelayString = "9000")
public void scheduledMethod() {
      System.out.println(" Scheduler with Fixed delay and Initial Delay:" + new Date());
}

@Scheduled with fixedRate

The fixedRate attribute represents the interval for executing a job at a fixed interval of time. The execution time of the method is not considered when deciding when to start the next job.

@Scheduled(fixedRate = 4000)
// @Scheduled(fixedRateString = "4000")
public void scheduledMethod() {
      System.out.println(" Scheduler with Fixed Rate :" + new Date());
}

In case of fixedRate, the scheduled task will run at every 4000 milliseconds(4 seconds).ย It doesnโ€™t check for any previous executions of the task.

ISO Duration Format for fixedDelayString, initialDelayString & fixedRateString

In the above examples, we have provided the time intervals in milliseconds. It is fine to provide small values in milliseconds, but if values are large, representation in milliseconds will become difficult to read. For example, the milliseconds representation for one hour will be 3600000. On the other hand, if we use ISO duration Format, it will be represented as โ€˜PT01Hโ€™. Letโ€™s understand it with the help of below chart and an example:

Spring Scheduling Annotations With Examples

@Scheduled(fixedDelayString = "PT20M") 
public void scheduledMethod() {
  ย  ย  System.out.println(" Scheduler with Fixed delay:" + new Date()); 
}

Here, โ€˜PT20Mโ€™ represents 20 minutes, which is 1200000 in milliseconds. Similarly, we can represent initialDelayString & fixedRateString to specify a time interval in this format.

Moreover, we can also set these intervals as a property in our application.properties file. For example, the property named delay is set to 30 seconds in the duration format โ€˜PT30Sโ€™ as shown below.

@Scheduled(fixedDelayString = "${delay}")
delay=PT30S

@Scheduled Spring Boot with cron

Sometimes fixedDelay & fixedRate donโ€™t solve our purpose. In that case we should use cron expressions as it provides more flexible options. For example, below code demonstrates that the scheduled task will execute every year on Feb 14th 9:00:00 AM
if the given day(14th) is Sunday or Tuesday only.

@Scheduled(cron = "0 0 9 14 2 SUN,TUE")
public void scheduledMethod() {
     System.out.println("Hello cron Scheduler :" +new Date());
}

Moreoever, we can also use the zone attribute to modify this timezone as below. By default, Spring considers the serverโ€™s local time zone for evaluation of the cron expression.

@Scheduled(cron = "0 0 9 14 2 SUN,TUE", zone = "America/New_York")

Furthermore, to get familiar with the variety of cron expressions, kindly visit a separate article on โ€˜Spring Boot Scheduler Cron Expressionsโ€˜.

CRON Macros

Spring also supports cron macros to represent most commonly used time intervals to improve code readability. Below macros are supported by Spring.

1) @hourly

2) @yearly

3) @monthly

4) @weekly

5) @daily

For example, below code snippet illustrates the usage of cron macros.

@Scheduled(cron = "@daily")

@Schedules

We can even configure multiple @Scheduled rules using @Schedules annotation. For example, below code demonstrates the concept:

@Schedules({ 
           @Scheduled(fixedRate = 4000), 
           @Scheduled(cron = "0ย  ย 0ย  ย 0ย  ย 14ย  ย 2ย  *")
})
void getValentineDayNotification() { .... }

As shown in the example above, we have used two types of @Schedules rules.

In order to learn complete Scheduling with basics in Spring Boot, kindly visit our article on Spring Boot Scheduler.

Furthermore, for a separate article specific to cron expressions with improvements in Spring 5.3, visit Spring Scheduling Cron Expressions & Improvements.

Leave a Reply


Top