我使用下面的代码来运行计划任务。在运行时,我从spring上下文中删除了这个bean。为什么任务仍未停止。
@Service
@EnableScheduling
public class MyScheduler {
@Scheduled(cron = "0 0/1 * * * ?")
public void schedule() {
// task here
}
}
答案 0 :(得分:1)
它为我工作:
@Controller
@RequestMapping("/scheduler")
public class SchedulerController {
@Autowired
AbstractApplicationContext context;
@Autowired
ThreadPoolTaskScheduler scheduler;
@RequestMapping("/stop")
@ResponseBody
public String stop() {
// scheduler.shutdown();
BeanDefinitionRegistry factory = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();
factory.removeBeanDefinition("MyScheduler");
return "stoped";
}
}
@Service("MyScheduler")
@EnableScheduling
public class MyScheduler {
@Scheduled(cron = "0/10 * * * * ?")
public void schedule() {
System.out.println("> Running scheduler .... " + System.currentTimeMillis());
}
}
另一种方法是向调度程序添加一些“启用”功能。标志:
@Service("MyScheduler")
@EnableScheduling
public class MyScheduler {
boolean enable = true;
@Scheduled(cron = "0/10 * * * * ?")
public void schedule() {
if(enable){
System.out.println("> Running scheduler .... " + System.currentTimeMillis());
}
}
}
然后可以很简单地启用和禁用调度程序。