Spring boot 动态的配置Scheduling
一:springboot配置静态定时任务
1:pom中添加依赖
2:启动类中加入@EnableScheduling来开启定时任务
3:@Scheduled(cron = "0/10* * * * ?")// 每过10秒执行一次
二: springboot动态配置定时任务:主要动态的配置。
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
@Component
@Configuration
public class DynamicSchedulingConfig {
@Autowired
private ThreadPoolTaskSchedulerthreadPoolTaskScheduler;
@Bean
public ThreadPoolTaskSchedulerthreadPoolTaskScheduler(){
return new ThreadPoolTaskScheduler();
}
private ScheduledFuturefuture;
private Stringcron ="";
public StringgetCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
stopCron();
future =threadPoolTaskScheduler.schedule(new Runnable() {
@Override
public void run() {
try {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}catch (Exception e) {
e.printStackTrace();
}
}
}, new Trigger() {
@Nullable
@Override
public DatenextExecutionTime(TriggerContext triggerContext) {
if("".equals(cron)||cron==null){
return null;
}
CronTrigger cronTrigger =new CronTrigger(cron);
Date nextExeDate = cronTrigger.nextExecutionTime(triggerContext);
return nextExeDate;
}
});
}
public void stopCron(){
if(future!=null){
future.cancel(true);
}
}
}