运行时动态修改@Scheduled注解的定时任务
作者:互联网
@RestController @RequestMapping("api/v1/scheduler") public class TestController { @Autowired private ApplicationContext applicationContext; @GetMapping("/test") public String test(String sch) throws NoSuchFieldException, IllegalAccessException { ScheduledAnnotationBeanPostProcessor postProcessor = applicationContext.getBean(ScheduledAnnotationBeanPostProcessor.class); Field registrar = postProcessor.getClass().getDeclaredField("registrar"); registrar.setAccessible(true); ScheduledTaskRegistrar taskRegistrar = (ScheduledTaskRegistrar)registrar.get(postProcessor); Set<ScheduledTask> scheduledTaskSet = postProcessor.getScheduledTasks(); for(ScheduledTask scheduledTask : scheduledTaskSet){ if (scheduledTask.getTask().getRunnable().toString().equals("定时任务方法全类名")){ scheduledTask.cancel(); taskRegistrar.scheduleCronTask(new CronTask(scheduledTask.getTask().getRunnable(), sch)); } } return "hello test"; } @Scheduled(cron = "0/1 * * * * ? ") public void sch(){ System.out.println("测试定时任务==" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
标签:Scheduled,scheduledTask,sch,registrar,postProcessor,test,注解,定时,public 来源: https://blog.csdn.net/Leftmumu/article/details/116301852