springboot動態配置定時任務時間

springboot 動態配置定時任務時間

  • 需要實現 SchedulingConfigurer 接口
  • 類上添加啓動定時任務註解 @EnableScheduling
  • 添加 @Component 註冊爲 bean
例子如下
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@EnableScheduling
public class SchedulerJobs implements SchedulingConfigurer {

   private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

   @Value("${server.scheduler.cron}")
   private String cron;
   @Autowired
   private Service Service;

   @Override
   public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

       taskRegistrar.addTriggerTask(() -> {
           // 需要實現的任務邏輯
           service.doWork();
           
           logger.info("定時任務: " + "時間:【{}】",
                   new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
       }, triggerContext -> {
           //任務觸發,可修改任務的執行週期
           CronTrigger trigger = new CronTrigger(getCron());
           Date nextExec = trigger.nextExecutionTime(triggerContext);
           return nextExec;
       });
   }

   private String getCron() {
       if (StringUtils.isBlank(cron)) {
           cron = "0 0 * * * *";
       }
       return cron;
   }
}
配置文件application.properties
server.scheduler.cron=0 0 * * * *
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章