简体   繁体   中英

How to start/stop @Scheduled task after certain method finishes

I have a scheduled task that start working when application context loads and runs forever until program ends.

I'd like to save some resources and run scheduled task only when it's needed.

Here is abstract code I imagine how it should work like.

@EnableScheduling    
public class Scheduling {
    
        @Scheduled(fixedRate = 1000)
        public void scheduledTask() {
           log.info("scheduled task has been started");
        }
    
        public void triggerStart() {
           log.info("after this @Scheduled task will start working");
        }
    
        public void triggerFinish() {
           log.info("after this @Scheduled task will stop working");
        }
}

I'm curious is it possible to achieve such result?

A very simple way is to add a boolean switch:

@Scheduled(fixedRate = 1000)
public void scheduledTask() {
   if (enabled) {
       log.info("scheduled task has been started");
   }
}

public void triggerStart() {
   enabled = true;
   log.info("after this @Scheduled task will start working");
}

public void triggerFinish() {
   enabled = false;
   log.info("after this @Scheduled task will stop working");
}

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