Java 通过从上下文中删除bean定义在运行时停止spring任务调度器不起作用

Java 通过从上下文中删除bean定义在运行时停止spring任务调度器不起作用,java,spring,spring-scheduled,Java,Spring,Spring Scheduled,我正在使用下面的代码运行计划任务。在运行时,我从spring上下文中删除了这个bean。为什么任务仍然没有停止 @Service @EnableScheduling public class MyScheduler { @Scheduled(cron = "0 0/1 * * * ?") public void schedule() { // task here } } 这对我来说很有用: @Controller @RequestMapping("/

我正在使用下面的代码运行计划任务。在运行时,我从spring上下文中删除了这个bean。为什么任务仍然没有停止

@Service
@EnableScheduling
public class MyScheduler {

    @Scheduled(cron = "0 0/1 * * * ?")
    public void schedule() {
        // task here
    }

}
这对我来说很有用:

@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());
        }
    }
}
然后就可以简单地启用和禁用调度程序