首页 > 解决方案 > Spring Boot 中 @Scheduled 的动态配置

问题描述

我正在尝试使用配置文件动态配置 Spring Boot 计划。

目标是在 my 中包含以下内容application.yml

platform:
  plata:
    schedule:
      cron: '0 0 9 * * *'
  platb:
    schedule:
      initialDelay = 20000
      fixedDelay = 10000000

我正在努力解决的是我现在如何将此配置应用于@Scheduled注释。我在想类似以下的事情:

Scheduler.java:

@Scheduled("${platform.plata.schedule}")
public void plata() throws CalculationException {
    ...
}

@Scheduled("${platform.platb.schedule}")
public void platb() throws CalculationException {
    ...
}

标签: javaspring-bootyamlspring-scheduled

解决方案


在配置中使用属性的完整路径。

玉米表达式应该0 0 9 * * *注意没有' -chars

@Scheduled(cron="${platform.plata.schedule.cron}")
public void withCron() {
    // 
}

@Scheduled(initialDelayString = "${platform.platb.schedule.initialDelay}" ,fixedDelayString= "${platform.platb.schedule.fixedDelay}")
public void withFixedDelay() {
    // 
}

推荐阅读