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

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

我希望根据cron表达式安排大多数任务,有些只启动一次,启动后固定延迟,然后再也不会(即SimpleTriggerBean上的repeatCount设置为0 )。

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

如果你看一下Task namespace XSD ,你会发现只有三种不同的配置类型: fixed-delayfixed-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); } } 

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

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

     

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

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

         

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

    

我的工作范例:

      

这有效,并且比其他答案更容易。

  // Will fire the trigger 1 + repeatCount number of times, start delay is in milliseconds simple name: 'mySimpleTrigger', startDelay: 5000, repeatCount: 0