eztam
eztam

Reputation: 3829

Spring Cron scheduler “disable pattern”

My application loads some cron patterns from a properties file. I'm using the @Scheduled annotation like this:

@Scheduled(cron = "${config.cronExpression:0 0 11,23 * * *}")

Now I want to disable some tasks and the easiest solution would be to enter a cron pattern which will never run. In order to do this, I thought about using a cron expression that only executes at a specific day in the past. But unfortunately the Spring cron expressions don't allow to add a year or a date in the past.

Is there any pattern that will never run?

Upvotes: 45

Views: 49893

Answers (3)

M. Justin
M. Justin

Reputation: 21074

As of Spring 5.1.0 the @Scheduled annotation can accept "-" as the cron expression to disable the cron trigger.

Per the Javadocs:

The special value "-" indicates a disabled cron trigger, primarily meant for externally specified values resolved by a ${...} placeholder.


Care must be taken if this value is used within a properties YAML file, as the hyphen has a special syntactical meaning in YAML of denoting a list entry. An easy solution is to put quotes around it so that it's interpreted as a literal string instead of a list entry:

cron-expression: "-"

Upvotes: 95

vsingh
vsingh

Reputation: 6749

If it was a cron expression (NOT spring scheduler), you could have used below which makes the cron run on 2099

59 59 23 31 12 ? 2099

But spring scheduler does not take a year as input. This is what I have found to defer it for some extended period. Below will run on 29 Feb which will be a leap year.

0 0 0 29 2 ?

Upvotes: 8

icyerasor
icyerasor

Reputation: 5242

If you're stuck pre Spring 5.1.0 (SpringBoot < 2.1), your only option may be to disable the bean/service with the @Scheduled method altogether, for example by using a @ConditionalOnProperty("my.scheduleproperty.active") annotation and not setting the property (or setting it to false)

Upvotes: 6

Related Questions