How to conditionally enable or disable scheduled jobs in Spring?

前端 未结 11 1417
轻奢々
轻奢々 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:46

    You can also create a Bean based on condition and that Bean can have a Scheduled method.

    @Component
    @Configuration
    @EnableScheduling
    public class CustomCronComponent {
        @Bean
        @ConditionalOnProperty(value = "my.cron.enabled", matchIfMissing = true, havingValue = "true")
        public MyCronTask runMyCronTask() {
            return new MyCronTask();
        }
    }
    

    and

    @Component
    public class MyCronTask {
        @Scheduled(cron = "${my.cron.expression}")
        public void run() {
            String a = "";
        }
    }
    

提交回复
热议问题