Issue
I have a Spring scheduled method that is periodically run:
@Scheduled(cron = "${spring.cron.expression}")
public void demonJob() { ... }
The cron expression is successfully read from the application.properties
:
spring.cron.expression=0 0 * * * *
Now, I want to deploy my application to a special environment on which this particular scheduled method is not supposed to run. If I leave the cron property empty like this...
spring.cron.expression=
... I get the following exception:
Encountered invalid @Scheduled method 'demonJob': Cron expression must consist of 6 fields (found 0 in "")
How can I disable the Scheduled method elegantly, ideally only by providing a different setting in application.properties
?
Solution
Empty string is an incorrect cron expression. If you want to disable scheduler in particular condition just use @Profile
annotation or if you have to operate on property use @ConditionalOnProperty
annotation from Spring Boot.
@Component
@ConditionalOnProperty(prefix = "spring.cron", name = "expression")
public class MyScheduler {
@Scheduled(cron = "${spring.cron.expression}")
public void demonJob() throws .. { .. }
}
Answered By - Jakub Kubrynski