@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()));
}
}