How can you configure scheduled tasks in Spring Boot?
In Spring Boot, there are two ways to configure scheduled tasks.
- Scheduled tasks.
- Scheduled at scheduled時間
- Execute this task every 5 seconds.
- Activate scheduling
The sample code is as follows:
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Scheduled(cron = "0/5 * * * * *")
public void task() {
// 定时任务逻辑
System.out.println("定时任务执行...");
}
}
- able to be executed
- Able to be called or contacted.
- executes the function
- Bean
- Someone or something that is able to be run or put into motion.
- able to be called
The code example is as follows:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Runnable task() {
return () -> {
// 定时任务逻辑
System.out.println("定时任务执行...");
};
}
}
It is important to note that both of the above approaches require adding the corresponding annotation to the Spring Boot startup class to enable support for scheduled tasks.