简体   繁体   中英

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?

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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