Reputation: 11940
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
?
Upvotes: 14
Views: 17553
Reputation: 21347
As of Spring 5.1.0, the special cron value "-" can be used with the @Scheduled
annotation to disable the cron trigger.
The special value "-" indicates a disabled cron trigger, primarily meant for externally specified values resolved by a ${...} placeholder.
For your specific example, you merely need to set the spring.cron.expression
variable to this value. If this is a Spring Boot project, you can use one of the many externalized configuration options available for this purpose, including:
If this is not a Spring Boot project, you can still specify this property, though the mechanism to do so is going to be less standard and more project specific.
Upvotes: 12
Reputation: 18255
I could give another approach. Just redefine applicatino cron expression in any way to set unreachable time period. E.g. spring.cron.expression=1 1 1 1 1 ?
(this is I use in my code and it is enough for me).
Profit of this approach is that you do not have to do any additional changes in the code.
Upvotes: 1
Reputation: 3074
Possible Solution to your Question
Upvotes: 0
Reputation: 14159
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 .. { .. }
}
Upvotes: 8