首页 > 其他分享 >@Scheduled 如何读取动态配置文件

@Scheduled 如何读取动态配置文件

时间:2023-01-22 15:11:06浏览次数:37  
标签:Scheduled 读取 配置文件 cron day 表达式

@Scheduled 如何读取动态配置文件

@Scheduled读取动态配置文件

application.yml配置文件得配置信息

agreeAccTask:

每3分钟执行一次,handTime: 0 0/3 * * * ? 每天晚上2点 handTime: 0 0 2 * * ?

指定几天内: day 1 表示当前天内,2表示二天内,依次类推

指定生成目录路劲: dir F:/agreeacc

time: 0 0 2 * * ?

day: 1

dir: F:/agreeacc3

java后端

  • @Description:支付宝代扣对账文件定时生成

*/

@Slf4j

@Component

@EnableScheduling

public class AgreeAccTask {

@Autowired

private AgreeAccMapper agreeAccMapper;

@Value("${agreeAccTask.day}")

private String day;

@Value("${agreeAccTask.dir}")

private String dir;

@Scheduled(cron="${agreeAccTask.time}")

public void AgreeAccTask(){

    String today=DateUtil.date2String(new Date(),DateUtil.PATTERN_DATE);

    log.info("【生成代扣对账文件开始】日期:"+today);

    int j=Integer.parseInt(day);

SpringBoot @Scheduled 读取配置文件获取croerWWbrHn值

1、在类上加注解@Component,交给Spring管理

2、在@PropertySource指定配置文件名称,如下配置,指定放在src/main/resource目录下的application.properties文件

3、配置文件application.properties参考内容如下

每秒钟执行一次

cron=0/1 * * * * *

import org.springframework.context.annotation.PropertySource;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

@Component

@PropertySource("classpath:/application.properties")

public class ScoreTask1 {

@Scheduled(cron="${cron}")

public void scoreTask(){

System.out.println("从配置文件读取cron表达式定时器");

}

}

进一步衍生,可以把开发环境跟生产环境cron表达式做环境隔离,这样每次打包部署,系统自动执行配置文件cron表达式,减少手动修改代码次数。

这里推荐一个在线生成cron表达式的工具 在线Cron表达式生成器

注意cron表达式只能配置6位参数,即 秒分时 日月周,有时候生成器会生成7位参数,这样在java代码执行会报错的

标签:Scheduled,读取,配置文件,cron,day,表达式
From: https://www.cnblogs.com/dituirenwu/p/17064448.html

相关文章