8

我正在调查以固定速率使用@Scheduled,在某些可配置的情况下,不应运行计划的作业。

文档没有提到这一点,但分别是fixedDelay()和的默认值。这些可以用来可靠地确保计划的方法不会触发吗?fixedDelayString()-1""

4

2 回答 2

6

你不能。当您将fixedDelay属性设置为-1或尝试使用@Scheduled而未为其任何属性指定有效值时,Spring 将抱怨未设置任何属性:

'cron''fixedDelay(String)''fixedRate(String)'属性中的一个是必需的

您可以通过查看源代码来验证此行为ScheduledAnnotationBeanPostProcessor#processScheduled

它包含如下逻辑:

boolean processScheduled = false;

// ...

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

// ...

Assert.isTrue(processedSchedule, errorMessage);

查看此SO 帖子,了解有条件禁用的一些选项@Scheduled

于 2015-10-05T11:11:30.137 回答
1

如 spring 文档中所述,您可以指定"-"禁用触发任务:

CRON_DISABLED:表示禁用触发器的特殊 cron 表达式值: "-"

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

于 2021-12-24T09:55:10.200 回答