8月6

SpringBoot @Scheduled 从配置文件获取cron值

| |
22:53编程杂谈  From: 本站原创
今天有个同事说要我帮他看下怎么把这个定时任务的cron表达式放到配置文件里面去,
1、在类上加注解@Component,交给Spring管理
2、在@PropertySource指定配置文件名称,如下配置,指定放在src/main/resource目录下的application.yml文件
3、配置文件application.yml参考内容如下
application.yml

jobs:
  customDictUpdateTime:
    corn: "0/5 * * * * ?"


@Configuration
@Component
@Slf4j
@PropertySource(value = "classpath:application.yml")
public class QuartzTask {

    @Autowired
    private RedisUtil redisUtil;

    private static boolean startTask = true;

    @PostConstruct
    public void startInit() {
        excuteBusiness();
    }

    //定时任务初始化政务宝自定义词库
   //如果获取不到, 取冒号后面的默认值
    @Scheduled(cron = "${jobs.customDictUpdateTime.corn:0/5 * * * * ?}")
    public void excuteTask() {
        excuteBusiness();
    }



上面说的是yml配置文件,有的同学就说了,那么我用的application.properties文件配置呢?

application.properties

jobs.customDictUpdateTime.corn=0/5 * * * *

import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Configuration
@Component
@Slf4j
@PropertySource(value = "classpath:application.properties")
public class QuartzTask {

    @Autowired
    private RedisUtil redisUtil;

    private static boolean startTask = true;

    @PostConstruct
    public void startInit() {
        excuteBusiness();
    }

    //定时任务初始化政务宝自定义词库
   //如果获取不到, 取冒号后面的默认值
    @Scheduled(cron = "${jobs.customDictUpdateTime.corn:0/5 * * * * ?}")
    public void excuteTask() {
        excuteBusiness();
    }





来源:Heck's Blog
地址:https://www.heckjj.com/post/543/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!
阅读(848) | 评论(0) | 引用(0)