springboot在配置文件中控制 @Scheduled 开关

时间:2025-03-23 07:32:58

springboot在配置文件中控制 @Scheduled 开关

详见: /a/1190000018805591

配置文件
//控制项目中所有@Scheduled定时任务开关
enable:
  scheduled: false
方法一
代码

新建ScheduledCondtion(类名随意)并实现Condition ,用来读取配置文件中的开关,返回一个boolean类型的参数

//Condition 引用 import ;
public class ScheduledCondtion implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //读取配置中的属性
        return Boolean.valueOf(conditionContext.getEnvironment().getProperty(""));
    }
}

通过@Configuration定义一个配置类ScheduledConfig(类名随意),通过@ConditionalScheduledCondtion为条件,来决定是否创建 bean。

@Configuration
public class ScheduledConfig {
    @Conditional(ScheduledCondtion.class)
    @Bean
    public ScheduledAnnotationBeanPostProcessor processor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }
}

通过编辑配置文件enable: scheduled: false/true进行测试

@Scheduled(cron = "*/5 * * * * ?")
    public void scheduled(){
        System.out.println("定时5秒");
    }
方法二

通过@Configuration定义一个配置类ScheduledConfig(类名随意),添加启用定时任务注解@EnableScheduling,通过@ConditionalOnProperty注解来控制@Configuration是否生效。

@Configuration
@EnableScheduling //启用定时任务
//配置文件读取是否启用此配置
@ConditionalOnProperty(prefix = "enable", name = "scheduled", havingValue = "true")
public class SchedulingConfig {
}
注意:将系统中启动类上和配置类中的@EnableScheduling注释或者删除