2011-10-11 78 views
1

我需要配置超出Spring内部调度功能的调度算法(基本上“每隔5分钟,但仅在4:00和16:00之间”)。看起来,实现org.springframework.scheduling.Trigger接口是一条非常简单的路。如何在Spring 3中配置自定义触发器?

我无法弄清楚的部分,似乎并没有在the documentation中得到解答:这是如何与XML配置混合的?似乎没有任何方法可以在任务命名空间的元素中指定自定义触发器bean(除了Quartz示例)。

如何在Spring 3应用程序中使用自定义触发器?理想情况下使用Bean XML配置。

回答

5

看看DurationTrigger我写了一年前。

public class DurationTrigger implements Trigger { 

    /** 
    * <p> Create a trigger with the given period, start and end time that define a time window that a task will be 
    *  scheduled within.</p> 
    */ 
    public DurationTrigger(Date startTime, Date endTime, long period) {...} 

    // ... 
} 

这里是你将如何安排这样的任务与此触发器:

Trigger trigger = new DurationTrigger(startTime, endTime, period); 
ScheduledFuture task = taskScheduler.schedule(packageDeliveryTask, trigger); 

或者,你可以使用CronTrigger/cron表达式:

<!-- Fire every minute starting at 2:00 PM and ending at 2:05 PM, every day --> 

<task:scheduled-tasks> 
    <task:scheduled ref="simpleProcessor" method="process" cron="0 0-5 14 * * ?"/> 
</task:scheduled-tasks> 

看看这个JIRA为以及此弹簧整合article

编辑

从JIRA的讨论,可以配置上面的DurationTrigger,或与此有关的任何其他自定义触发,使用Spring集成:

<inbound-channel-adapter id="yourChannelAdapter" 
         channel="yourChannel"> 
    <poller trigger="durationTrigger"/> 
</inbound-channel-adapter> 

<beans:bean id="durationTrigger" class="org.gitpod.scheduler.trigger.DurationTrigger"> 
    <beans:constructor-arg value="${start.time}"/> 
    <beans:constructor-arg value="${end.time}"/> 
    <beans:constructor-arg value="${period}"/> 
</beans:bean> 

它是使用Spring集成在非常简单的项目,即使你不打算。您可以尽可能少地使用上述调度部分,或者像Spring Integration提供的许多其他企业集成模式一样。

+0

谢谢,tolitius。我仍然不明白如何以编程方式计划重复任务(如果我是正确的,您的示例是单次发生的);我仍然觉得我无法通过XML配置来安排它(我需要相当于@cron属性)。我发现感谢你的帖子的原因是,现在cron触发器已经足够了。我不知何故忘了cron语法允许间隔 - '0 0/5 4-15 * *?'应该对我的用例正常工作。 –

+0

是的。而上面的'cron表达式'实际上是一个你正在寻找的XML配置:) – tolitius

+0

尽管如此,cron表达式有其局限性。我现在没有什么担心,但是我把它作为对JIRA票据的评论。 –

相关问题