Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to assign @Scheduled with a period representing "never" (in Spring)?

I'm investigating using @Scheduled at a fixed rate where in some configurable circumstances the scheduled job should never be run.

The documentation doesn't mention this but the default values for fixedDelay() and fixedDelayString() are -1 and "" respectively. Can these be used to reliably ensure that the scheduled method doesn't fire?

like image 496
Steve Chambers Avatar asked Oct 05 '15 10:10

Steve Chambers


People also ask

What is @scheduled annotation in Spring?

The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.

Is @scheduled asynchronous?

There is no need to use @Async. Just use fixedRate attribute of @Scheduled instead of fixedDelay. Spring will make another invocation on the method after the given time regardless of any call is already being processed.


2 Answers

You can not. When you set the fixedDelay attribute to -1 or attempt use @Scheduled without specifying a valid value for any of its attributes, Spring will complain that no attribute is set:

Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required

You can verify this behavior by going through the source code of ScheduledAnnotationBeanPostProcessor#processScheduled.

It contains logic like:

boolean processScheduled = false;

// ...

if (fixedRate >= 0) {
    Assert.isTrue(!processedSchedule, errorMessage);
    processedSchedule = true;
    this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
}

// ...

Assert.isTrue(processedSchedule, errorMessage);

Take a look at this SO post for some options for conditionally disabling @Scheduled.

like image 194
Bohuslav Burghardt Avatar answered Oct 27 '22 10:10

Bohuslav Burghardt


As mentioned in spring docs, you can specify "-" to disable the triggering of the task:

CRON_DISABLED: A special cron expression value that indicates a disabled trigger: "-".

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#CRON_DISABLED

like image 23
Hüseyin Yağlı Avatar answered Oct 27 '22 09:10

Hüseyin Yağlı