2011-10-11 79 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票據的評論。 –

相關問題