How to conditionally enable or disable scheduled jobs in Spring?

前端 未结 11 1343
轻奢々
轻奢々 2020-11-28 07:26

I am defining scheduled jobs with cron style patterns in Spring, using the @Scheduled annotation.

The cron pattern is stored in a config properties file

相关标签:
11条回答
  • 2020-11-28 07:51

    If you are looking to toggle @EnableScheduling from a property you can do this in Spring Boot by moving the @EnableScheduling annotation to a configuration class and use @ConditionalOnProperty as follows:

    @Configuration
    @EnableScheduling
    @ConditionalOnProperty(prefix = "com.example.scheduling", name="enabled", havingValue="true", matchIfMissing = true)
    public class SchedulingConfiguration {
    
    }
    

    This will disable scheduling for the application. This may be useful in a situation where you want to be able to run the application once or scheduled depending on how it's being started.

    From wilkinsona's comment on here: https://github.com/spring-projects/spring-boot/issues/12682

    0 讨论(0)
  • 2020-11-28 07:55

    Your question states to condition the actual creation of the bean. You can do this easily with this parameter by using @Profile if you are using at least Spring 3.1.

    See the documentation here: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/Profile.html

    0 讨论(0)
  • 2020-11-28 07:55

    I know my answer is a hack, but giving a valid cron expression that never executes may fix the issue (in the environment specific configuration), Quartz: Cron expression that will never execute

    0 讨论(0)
  • 2020-11-28 07:59

    You can group schedule methods by conditions into number of services and init them like this:

    @Service
    @ConditionalOnProperty("yourConditionPropery")
    public class SchedulingService {
    
    @Scheduled
    public void task1() {...}
    
    @Scheduled
    public void task2() {...}
    
    }
    
    0 讨论(0)
  • 2020-11-28 08:00
    @Component
    public class ImagesPurgeJob implements Job {
    
        private Logger logger = Logger.getLogger(this.getClass());
    
        @Value("${jobs.mediafiles.imagesPurgeJob.enable}")
        private boolean imagesPurgeJobEnable;
    
        @Override
        @Transactional(readOnly=true)
        @Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
        public void execute() {
    
             //Do something
            //can use DAO or other autowired beans here
            if(imagesPurgeJobEnable){
    
                Do your conditional job here...
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题