Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 872
smeeb Avatar asked Jun 03 '26 15:06

smeeb


1 Answers

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

like image 161
pvpkiran Avatar answered Jun 06 '26 04:06

pvpkiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!