Making Spring Boot cron tasks configurable

2019-02-20 04:32发布

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!

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.

2条回答
We Are One
2楼-- · 2019-02-20 05:20

You can make the cron expression configurable like this

@Scheduled(cron ="${some.trigger}") 

You can set this value from your application.properties file for dev/prod profiles. So in test mode you can set this to whatever value you want using profile specific properties file, for example application-test.properties

查看更多
乱世女痞
3楼-- · 2019-02-20 05:29

You can annotate:

@Profile("!test")
@Component
public class MyTask {

Then test application properties should contain:

spring:
  profiles: test

This would disable task execution in test mode.

I would move the code executed by the task to a separate method and test it individually without scheduling / waiting.

查看更多
登录 后发表回答