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?
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.
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With