Search code examples
spring-bootcronscheduled-tasks

Making Spring Boot cron tasks configurable


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.


Solution

  • 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. In test mode you can set this to whatever value you want using profile specific properties file, for example application-test.properties