Spring Boot Scheduling With Annotation

2017-04-19 cron EnableScheduling scheduler SchedulingConfigurer spring-boot

Reading time: 2 Min(s)

Introduction

Spring Boot provides annotation support for task scheduling. It is easy way to develop and run a Task scheduler without using any xml and bean configurations Simply add the annotation @Scheduled on the task scheduler method with required interval time. In this example, we will see how to use Spring @Scheduledannotation to schedule a task.

Enable scheduling annotations

To enable support for @Scheduled annotation add @EnableScheduling to one of your @Configuration classes:

@Configuration
@EnableScheduling
public class AppConfig {
}

You are free to pick and choose the relevant annotations for your application. For example, for more fine-grained control you can additionally implement the SchedulingConfigurer interfaces.

The @Scheduled annotation

The @Scheduled annotation can be added to a method along with trigger metadata.

Important: The simple rules that need to be followed to annotate a method with @Scheduled are:

  • A method should not accept any parameters

  • A method should have void return type

For example, the following method would be invoked every 5 seconds with a fixed delay, meaning that the period will be measured from the completion time of each preceding invocation.

@Scheduled(fixedDelay=5000)
public void doSomething() {
// something that should execute periodically
}

If a fixed rate execution is desired, simply change the property name specified within the annotation.

The following would be executed every 5 seconds measured between the successive start times of each invocation.

@Scheduled(fixedRate=5000)
public void doSomething() {
// something that should execute periodically
}

For fixed-delay and fixed-rate tasks, an initial delay may be specified indicating the number of milliseconds to wait before the first execution of the method.

@Scheduled(initialDelay=1000, fixedRate=5000)
public void doSomething() {
// something that should execute periodically
}

If simple periodic scheduling is not expressive enough, then a cron expression may be provided. For example, the following will only execute on weekdays.

@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}