在Spring Boot中,有兩種方式來配置定時任務:
@Scheduled注解來標記一個方法為定時任務??梢栽诜椒ㄉ鲜褂?code>@Scheduled注解來指定任務的執行時間表達式,如@Scheduled(cron = "0/5 * * * * *")表示每5秒執行一次。需要在啟動類上添加@EnableScheduling注解來開啟定時任務的支持。示例代碼如下:
@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("定時任務執行...");
}
}
Runnable或Callable接口,并在run()方法中編寫定時任務的邏輯。然后使用@Bean注解將實現類注入到Spring容器中。Spring Boot會自動檢測并執行實現了Runnable或Callable接口的Bean。示例代碼如下:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Runnable task() {
return () -> {
// 定時任務邏輯
System.out.println("定時任務執行...");
};
}
}
需要注意的是,以上兩種方式都需要在Spring Boot的啟動類上添加相應的注解來開啟定時任務的支持。