本篇文章小编给大家分享一下@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 读取配置文件获取cron值
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表达式,减少手动修改代码次数。