How to stop a scheduled task that was started using @Scheduled annotation?

后端 未结 8 1580
挽巷
挽巷 2020-11-27 03:52

I have created a simple scheduled task using Spring Framework\'s @Scheduled annotation.

 @Scheduled(fixedRate = 2000)
 public void doSomething() {}
         


        
8条回答
  •  清酒与你
    2020-11-27 04:35

    There is a bit of ambiguity in this question

    1. When you say "stop this task", did you mean to stop in such a way that it's later recoverable (if yes, programmatically, using a condition which arises with in the same app? or external condition?)
    2. Are you running any other tasks in the same context? (Possibility of shutting down the entire app rather than a task) -- You can make use of actuator.shutdown endpoint in this scenario

    My best guess is, you are looking to shutdown a task using a condition that may arise with in the same app, in a recoverable fashion. I will try to answer based on this assumption.

    This is the simplest possible solution that I can think of, However I will make some improvements like early return rather than nested ifs

    @Component
    public class SomeScheduledJob implements Job {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SomeScheduledJob.class);
    
        @Value("${jobs.mediafiles.imagesPurgeJob.enable}")
        private boolean imagesPurgeJobEnable;
    
        @Override
        @Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
        public void execute() {
    
            if(!imagesPurgeJobEnable){
                return;
            }
            Do your conditional job here...
       }
    

    Properties for the above code

    jobs.mediafiles.imagesPurgeJob.enable=true or false
    jobs.mediafiles.imagesPurgeJob.schedule=0 0 0/12 * * ?
    

提交回复
热议问题