Search code examples
javaspringspring-mvcscheduled-tasksspring-scheduled

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?


Solution

  • 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.