Reputation: 33
I'm using the code below to run a scheduled task. And at runtime I removed this bean from the spring context. Why the task is still not stopped.
@Service
@EnableScheduling
public class MyScheduler {
@Scheduled(cron = "0 0/1 * * * ?")
public void schedule() {
// task here
}
}
Upvotes: 1
Views: 1262
Reputation: 18767
Its work for me:
@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());
}
}
The alternative were to add to the scheduler some 'enable' flag:
@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());
}
}
}
Then it is simple possible to enable and disable the scheduler.
Upvotes: 1