39

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
eztam
  • 3,443
  • 7
  • 36
  • 54
  • 1
    I'm not sure if this helps, but I know we localy use the cron-expression 'none' successfully. But this might be a hack... Other people suggest using February 31th, or December 31th 2099... http://stackoverflow.com/questions/8324306/cron-job-that-will-never-execute http://stackoverflow.com/questions/13835221/quartz-cron-expression-that-will-never-execute/13938099#13938099 – samjaf Apr 04 '16 at 13:41

3 Answers3

76

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.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
  • 12
    Using this special value in a properties yml means you need to include the quotes. So, it's really `cron-expression: "-"` – J. S. Sep 24 '20 at 08:58
8

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 ?
Fabio Bonfante
  • 5,128
  • 1
  • 32
  • 37
vsingh
  • 6,365
  • 3
  • 53
  • 57
  • 2
    This is the better option if the value is being read from an external file and a code change is not desired – buddamus Dec 06 '19 at 15:08
6

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)

icyerasor
  • 4,973
  • 1
  • 43
  • 52