关于java:’initial-delay’属性不能与cron和触发任务一起使用

the 'initial-delay' attribute may not be used with cron and trigger tasks

我正在构建要运行的cron,服务器启动一段时间后,我需要运行其中一个cron。

1
2
<task:scheduled ref="myCron"
            method="processData" cron="0/15 * * * * ?" initial-delay="45000"></task:scheduled>

我需要每15秒钟运行一次该cron,它确实如此。但是我需要在45秒服务器启动后立即运行此cron,而不是立即启动。

下面是我的xsd,

1
2
3
4
5
6
7
8
9
10
11
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"

    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/task
            http://www.springframework.org/schema/task/spring-task-3.2.xsd"

    default-lazy-init="false">

异常

1
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: the 'initial-delay' attribute may not be used with cron and trigger tasks


ScheduledTasksBeanDefinitionParser的代码中,您可以看到croninitial-delay不兼容:

1
2
3
4
5
if (hasInitialDelayAttribute && (hasCronAttribute || hasTriggerAttribute)) {
                parserContext.getReaderContext().error(
                       "the 'initial-delay' attribute may not be used with cron and trigger tasks", taskElement);
                continue; // with the possible next task element
            }

您可能要使用固定延迟实现,例如:

1
<task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000"/>

请参阅第33.3.2节"触发器实现"中的Spring文档