使用Spring任务命名空间调度任务运行一次

Kar*_*son 15 java spring

我正在使用任务命名空间在spring中设置一个计划任务方案.

我想安排大部分任务根据cron表达式火,有的在启动后只启动一次,一个固定的延迟,然后再也没有(即什么设置repeatCount,以0将实现在SimpleTriggerBean).

是否有可能在任务命名空间中实现这一点,或者我是否需要恢复为我的触发器定义bean?

bac*_*car 15

如果您不需要初始延迟,则可以使其在启动时"仅运行一次",如下所示:

<task:scheduled-tasks>
    <!--  Long.MAX_VALUE ms = 3E8 years; will run on startup 
                  and not run again for 3E8 years --> 
    <task:scheduled ref="myThing" method="doStuff" 
                fixed-rate="#{ T(java.lang.Long).MAX_VALUE }" />
</task:scheduled-tasks>
Run Code Online (Sandbox Code Playgroud)

(当然,如果您认为您的代码运行时间超过3E8年,您可能需要采用不同的方法......)

如果你需要一个初始延迟,你可以按如下方式配置它(我正在使用Spring 3.1.1测试) - 这不需要任何额外的依赖项,你不必编写自己的触发器,但你必须配置PeriodicTriggerSpring提供的:

<bean id="onstart" class="org.springframework.scheduling.support.PeriodicTrigger" > 
    <!--  Long.MAX_VALUE ms = 3E8 years; will run 5s after startup and
               not run again for 3E8 years --> 
    <constructor-arg name="period" value="#{ T(java.lang.Long).MAX_VALUE }" /> 
    <property name="initialDelay" value="5000" /> 
</bean> 
<task:scheduled-tasks> 
    <task:scheduled ref="myThing" method="doStuff" trigger="onstart" /> 
</task:scheduled-tasks> 
Run Code Online (Sandbox Code Playgroud)

Spring 3.2似乎直接支持"initial-delay"属性,但我没有对此进行测试; 我猜这有效:

<task:scheduled-tasks>
    <task:scheduled ref="myThing" method="doStuff" 
                        fixed-rate="#{ T(java.lang.Long).MAX_VALUE }" 
                        initial-delay="5000"/>
</task:scheduled-tasks>
Run Code Online (Sandbox Code Playgroud)


aru*_*zca 13

我的工作范例:

<bean id="whateverTriggerAtStartupTime" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <property name="jobDetail" ref="whateverJob"/>
    <property name="repeatCount" value="0"/>
    <property name="repeatInterval" value="10"/>
</bean>
Run Code Online (Sandbox Code Playgroud)


Sea*_*oyd 7

如果你看看任务命名空间XSD,你会发现只有三个不同的配置类型:fixed-delay,fixed-ratecron.

如果查看ScheduledTasksBeanDefinitionParser的源代码,您将看到只评估其中一个值.以下是相关部分:

String cronAttribute = taskElement.getAttribute("cron");
if (StringUtils.hasText(cronAttribute)) {
    cronTaskMap.put(runnableBeanRef, cronAttribute);
}
else {
    String fixedDelayAttribute = taskElement.getAttribute("fixed-delay");
    if (StringUtils.hasText(fixedDelayAttribute)) {
        fixedDelayTaskMap.put(runnableBeanRef, fixedDelayAttribute);
    }
    else {
        String fixedRateAttribute = taskElement.getAttribute("fixed-rate");
        if (!StringUtils.hasText(fixedRateAttribute)) {
            parserContext.getReaderContext().error(
                    "One of 'cron', 'fixed-delay', or 'fixed-rate' is required",
                    taskElement);
            // Continue with the possible next task element
            continue;
        }
        fixedRateTaskMap.put(runnableBeanRef, fixedRateAttribute);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以没有办法结合这些属性.简而言之:命名空间不会让你到那里.