Spring Boot:从数据库获取@Scheduled cron值

Dan*_*iel 12 java cron scheduled-tasks spring-boot

我正在使用Spring Boot并且在调度cron task数据库中存在的使用值时遇到问题.

暂时,我正在读取属性文件中的值,如下所示:

@Scheduled(cron= "${time.export.cron}")
public void performJob() throws Exception {
   // do something
}
Run Code Online (Sandbox Code Playgroud)

这很好用,但我没有从属性文件中获取值,而是想从数据库表中获取它们.有可能吗?怎么样?

小智 11

您可以在SpringBootApplication主类或任何配置类中添加一个bean来从数据库中获取cron值。示例代码如下:

@Autowired
private CronRepository cronRepo;

@Bean
public int getCronValue()
{
    return cronRepo.findOne("cron").getCronValue();
}
Run Code Online (Sandbox Code Playgroud)

您应该创建一个表并在数据库中提供合适的值。之后,您可以在@Scheduled中提供bean。示例代码如下:

@Scheduled(cron="#{@getCronValue}")
Run Code Online (Sandbox Code Playgroud)

希望它能解决您的问题。

  • 它对我来说很好,但是我们需要在类级别添加@EnableScheduling才能运行/执行@Scheduled(cron =“#{@ getCronValue}”) (2认同)