使 Spring Boot cron 任务可配置 [英] Making Spring Boot cron tasks configurable
问题描述
Spring Boot 允许您像这样创建后台类似 cron"的任务:
Spring Boot allows you to create background "cron-like" tasks like so:
@Component
public class MyTask {
// Every hour on the hour
@Scheduled(cron = "0 0 0/1 1/1 * ? *")
public void doSomething() {
// blah whatever
}
}
这使得自动化集成测试有点困难!我不应该有一个运行集成测试只是挂一个小时,等待看看当我的任务在一个小时的顶部运行时会发生什么.我也不应该等到接近小时才运行我的测试,这样我就可以在接近小时确认正确的行为!
This makes automated integration testing a wee bit difficult! I shouldn't have to have a running integration testing just hanging for an hour, waiting to see what happens when my task runs at the top of the hour. Nor should I have to wait to run my test near the hour so that I can confirm proper behavior at the top of the hour!
有没有办法让这些 cron
值可配置? 这样,如果我想在测试模式"下运行我的应用程序,我可以安排 MyTask#doSomething()
方法运行,例如,每 30 秒等.
Is there a way to make these cron
values configurable? That way if I want to run my app in "test mode" I could schedule the MyTask#doSomething()
method to run, say, every 30 seconds, etc.
推荐答案
你可以像这样配置 cron 表达式
You can make the cron expression configurable like this
@Scheduled(cron ="${some.trigger}")
您可以从您的 application.properties
文件中为 dev/prod 配置文件设置此值.在测试模式下,您可以使用配置文件特定的属性文件将其设置为您想要的任何值,例如 application-test.properties
You can set this value from your application.properties
file for dev/prod profiles. In test mode you can set this to whatever value you want using profile specific properties file, for example application-test.properties
这篇关于使 Spring Boot cron 任务可配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!