SpringBoot通过修改配置文件控制任务定时器开关效果

本文展示了如何修改application.yml以控制定时任务的启用,并创建了一个名为AppIndexTask的类,该类使用@Scheduled注解执行定时任务。任务的执行取决于appindex.enabled属性在配置文件中的值。若值为true,则任务每两分钟运行一次。
摘要由CSDN通过智能技术生成

修改application.yml

appindex:
  enabled: true

创建定时任务类AppIndexTask


import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Configuration
//启用定时任务
@EnableScheduling
//配置文件读取是否启用此配置     实现是通过havingValue与配置文件中的值对比,返回为true则配置类生效,反之失效
@ConditionalOnProperty(prefix = "appindex", name = "enabled", havingValue = "true")
public class AppIndexTask {
    @Scheduled(cron = "0/2 * * * * ?")
    public void pppIndexTask() {
        try {
            System.out.println("定时任务开关测试");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值