简体   繁体   English

停止使用@Scheduled注释的计时器

[英]stop timer that using @Scheduled annotation

I have a simple job that using Spring Boot with scheduler annotation, it runs successfully but how can I pause or stop it? 我有一个简单的工作,使用Spring Boot和调度程序注释,它运行成功,但我怎么能暂停或停止它?

@Component
public class UpAndDown {
    @Scheduled(fixedRate = 2000)
    public void upAndDown() {}
}

The easiest way would be to have a flag that keeps track of whether this functionality is enabled or not. 最简单的方法是使用一个标志来跟踪是否启用了此功能。 Then, check that flag in your method: 然后,检查方法中的那个标志:

@Component
public class UpAndDown {
    private boolean triggerEnabled = true;

    public void setTriggerEnabled(boolean triggerEnabled) {
        this.triggerEnabled = triggerEnabled;
    }

    @Scheduled(fixedRate = 2000)
    public void upAndDown() {
        if(triggerEnabled) {
            doTheStuff();
        }
    }
}

This will obviously not stop the timer, but it will effectively do what you want it to do, without messing with the infrastructure beans. 这显然不会停止计时器,但它会有效地执行您想要的操作,而不会弄乱基础结构bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM