Spring 註解 @Scheduled(cron = "0 0/10 * * * ? ") 動態改變時間
阿新 • • 發佈:2018-11-13
lse config enables pre text div tor urn ring
import java.util.Date; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.Trigger;import org.springframework.scheduling.TriggerContext; 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; @Lazy(false) @Component @EnableScheduling public class DynamicScheduledTask implements SchedulingConfigurer { /** * 通過自動註入啟動任務調度 * * @Autowired * DynamicScheduledTask dynamicScheduledTask; **/ private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String DEFAULT_CRON = "0 0/10 * * * ? "; private String cron = DEFAULT_CRON; /** * 獲取任務執行規則 * @return */ public String getCron() { return cron; } /** * 設置任務執行規則 * @param cron */ public void setCron(String cron) { this.cron = cron; } @Bean(destroyMethod = "shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(20); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { //用於設置定時任務線程數,默認不設置的話為單線程 taskRegistrar.setScheduler(taskExecutor()); taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { // 任務邏輯 logger.debug("dynamicCronTask is running..."); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { // 任務觸發,可修改任務的執行周期 CronTrigger trigger = new CronTrigger(cron); Date nextExec = trigger.nextExecutionTime(triggerContext); return nextExec; } }); } }
Spring 註解 @Scheduled(cron = "0 0/10 * * * ? ") 動態改變時間