1.你的启动类上要有它
@SpringBootApplication @EnableScheduling public class JobApplication { public static void main(String[] args) { try { SpringApplication.run(JobApplication.class); System.out.println("JobApplication 启动成功。。。"); } catch (Exception e) { DpeLogUtil.error("JobApplication 启动失败", e); } } }
2.你得有一个执行定时任务,且监听动态cron的 Job
import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; 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.util.Date; @Component public class MyAlterTaskPushJob implements SchedulingConfigurer { //默认5秒执行一次 @Value("0/5 * * * * ?") private String cron; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { DpeLogUtil.resetLogFlag(null, LoggerNameEnum.JOB_LOGGER); taskRegistrar.addTriggerTask( new Runnable() { @Override public void run() { try { DpeLogUtil.info("MyAlterTaskPushJob#Runnable# cron={}", cron); DpeLogUtil.info("MyAlterTaskPushJob#Runnable# 做你的业务 boy"); }catch (Exception e) { } } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { DpeLogUtil.info("MyAlterTaskPushJob#Trigger# cron={}", cron); if (StringUtils.isBlank(cron)) { return null; } //定时任务触发,可修改定时任务的执行周期 CronTrigger cronTrigger = new CronTrigger(cron); Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext); return nextExecDate; } } ); } public String getCron() { return cron; } public void setCron(String cron) { this.cron = cron; } }
3.我们试一试去动态变更它
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; @Controller @RequestMapping("/alert") public class MyController { @Resource MyAlterTaskPushJob alterTaskPushJob; @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String update(Integer num){ String cron = "0/"+num+" * * * * ?"; alterTaskPushJob.setCron(cron); return "干你母"; } }
4.直接看效果
一开始,都是按照默认cron设置 5s执行一次
接着我们动态变更一下
接收到变更后,发现 cron动态变了,接下来看执行时间是否间隔发生变化
执行时段 已变成2s执行一次