Spring停止或开启定时器

 

ApplicaitonContext的额外功能依赖于bean的后置处理器

可以利用监听器完成定时器的开关

// 引入定时器
@EnableScheduling
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }
}
@Component(value = TaskScheduled.TASK)
public class TaskScheduled {

    public static final String TASK = "taskScheduled";

    @Autowired
    private ApplicationContext applicationContext;

    private AtomicInteger num = new AtomicInteger(0);

    @Scheduled(cron = "*/5 * * * * ?")
    public void task(){
        System.out.println("doing task...");

        // 自定义条件,条件满足之后启动或者停止监听器
        if(num.incrementAndGet() == 3){
            // 发布任务
            applicationContext.publishEvent(new DestroyEvent(applicationContext));
        }
    }
}

Event:

public class DestroyEvent extends ApplicationEvent {
    public DestroyEvent(Object object){
        super(object);
    }
}

 Listener:

@Component
public class DestroyListener implements ApplicationListener<DestroyEvent> {

    @Override
    public void onApplicationEvent(DestroyEvent destroyEvent) {
        Object object = destroyEvent.getSource();
        if(object instanceof ApplicationContext){
            //AbstractApplicationContext 实现了 ApplicationContext
            AbstractApplicationContext ap = (AbstractApplicationContext)object;

            //DefaultListableBeanFactory 实现了 ConfigurableListableBeanFactory
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)ap.getBeanFactory();

            // 如果工厂中有当前bean就销毁掉
            if(beanFactory.containsBean(TaskScheduled.TASK)){
                beanFactory.destroySingleton(TaskScheduled.TASK);
            }

            // 可以自定义再创建定时器
            // beanFactory.createBean(TaskScheduled.class);
        }
    }
}
    原文作者:尬聊师
    原文地址: https://blog.csdn.net/awkward_people/article/details/118085110
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞