使Spring Boot cron任务可配置 [英] Making Spring Boot cron tasks configurable

查看:305
本文介绍了使Spring Boot cron任务可配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆