How to disable @Scheduled method via properties file?

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 .. { .. }
}

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.

Tags:

Java

Spring