1. 程式人生 > >Springboot 配置實現定時任務

Springboot 配置實現定時任務

善於思考,擁抱變化,才能擁有未來

  在springboot專案中可以通過配置檔案來實現定時任務的輪詢,當然也可以將具體執行的corn表示式配置到資料庫,實現動態從資料庫獲取。

 1 @Configuration
 2 public class TestScheduleTask implements SchedulingConfigurer {
 3 
 4     @Value("${corn}")
 5     private String cornTime;
 6 
 7     @Override
 8     public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
9 taskRegistrar.addTriggerTask( 10 () -> { 11 // 定時具體任務 12 System.out.println("執行定時任務: " + LocalDateTime.now().toLocalTime()); 13 }, 14 triggerContext -> { 15 // 定時策略 16 return
new CronTrigger(cornTime).nextExecutionTime(triggerContext); 17 }); 18 } 19 20 }

  yml檔案為:

1 corn: 0 39 23 * * ?

  application增加@EnableScheduling開啟定時任務