This tutorial shows how to use @Scheduled Annotation to periodically run methods (in the future).
To schedule a Method you just need to use @Scheduled(fixedDelay=5000) Annotation.
To enable @Scheduled Annotation you need to add @EnableScheduling to some @Configuration Class.
Method's Class must be declared as Spring Component for Spring to detect it.
In this example this is achieved also by @Configuration (so @Configuration has dual role in this example).
@Scheduled Parameters (milliseconds)
@Scheduled(fixedRate = 5000) //Measured from the START of previous task
@Scheduled(fixedDelay = 5000) //Measured from the END of previous task
@Scheduled(fixedDelay = 5000, initialDelay = 1000) //Delay before first execution
@Scheduled(cron="*/5 * * * * MON-FRI") //Execute on weekdays
Application Schema [Results]
Spring Boot Starters
Create Project: springboot_taskscheduler.tasks (add Spring Boot Starters from the table)
Create Package: tasks (inside main package)
– Create Class: MyTasks.java (inside runners package)
MyTasks.java
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class MyTasks {
@Scheduled(fixedDelay=5000)
public void task1() {
System.out.println("Hello from task1()");
}
}