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

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

详见: https://segmentfault.com/a/1190000018805591

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

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

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

通过@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注释或者删除
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值