运行时动态修改@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()));
    }
}
上一篇:浅析SpringBoot如何做定时任务:@EnableScheduling和@Scheduled的使用、参数配置以及需要注意的内存问题


下一篇:定时任务 Scheduled quartz