Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable @Scheduled method via properties file?

Tags:

java

spring

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?

like image 539
Fritz Duchardt Avatar asked Jan 22 '16 09:01

Fritz Duchardt


People also ask

How do I turn off spring boot scheduler?

Canceling the Scheduled Future. Another way to stop the scheduler would be manually canceling its Future. In the cases with multiple scheduler tasks, then we can maintain the Future map inside of the custom scheduler pool but cancel the corresponding scheduled Future based on scheduler class.

How do I turn off Cron scheduler?

Stop a cron job You can stop a single cron job by removing its line from the crontab file. To do that, run the crontab -e command and then delete the line for the specific task. Alternatively, you can stop the cron job by commenting it out in the crontab file.


1 Answers

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:

  • Command line argument
  • Java System property
  • OS environment variable
  • Profile-specific application property for a profile used specifically for that environment

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.

like image 139
M. Justin Avatar answered Sep 20 '22 12:09

M. Justin