How to conditionally enable or disable scheduled jobs in Spring?

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

    We can disable the bean creation of the class having that scheduled methods using @Conditional annotation. This is very similar to @ConditionalOnProperty. This is used to conditionally spin up a bean on to the spring context. If we set the value to false, then the bean will not be spun up and loaded to spring. Below is the code.

    application.properties:

    com.boot.enable.scheduling=enable
    

    Condition:

    public class ConditionalBeans implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return "enabled".equalsIgnoreCase(context.getEnvironment().getProperty("com.boot.enable.scheduling"));
        }
    }
    

    My schedule class

    @Service
    @Conditional(ConditionalSchedules.class)
    public class PrintPeriodicallyService {
    
        @Scheduled(fixedRate = 3000)
        public void runEvery3Seconds() {
            System.out.println("Current time : " + new Date().getTime());
        }
    }
    

    This approach has a lot of flexibility where the condition generation is totally under our control.

提交回复
热议问题