How do I configure a custom trigger in Spring 3?
I need to configure a scheduling algorithm that is beyond the capabilities of Spring's in-build scheduling (basically "every 5 minutes, but only between 4:00h and 16:00h"). It seems that implementing the org.springframework.scheduling.Trigger interface is t开发者_Go百科he way to go, which seems simple enough.
The part I can't figure out and that doesn't seem to be answered in the documentation is: how does this mix with the XML configuration? There doesn't seem to be any way of specifying a custom trigger bean in the elements of the task namespace (apart from the Quartz example).
How do I use a custom trigger in a Spring 3 application? Ideally using the Bean XML configuration.
Take a look at DurationTrigger I wrote a year ago.
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 ) {...}
// ...
}
Here is how you would schedule such a task with this trigger:
Trigger trigger = new DurationTrigger( startTime, endTime, period );
ScheduledFuture task = taskScheduler.schedule( packageDeliveryTask, trigger );
Alternatively, you can use a CronTrigger / cron expression:
<!-- 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>
Check out this JIRA as well as this Spring Integration article
EDIT:
From the JIRA discussion, you can configure the DurationTrigger
above, or any other custom trigger for that matter, using Spring Integration:
<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>
It is quite simple to use Spring Integration in your project, even if you did not plan to. You can use as little as the above scheduling piece, or as much as relying on many other Enterprise Integration patterns that Spring Integration has available.
It seems using XML to configure any but the two standard triggers is not possible in Spring 3.0. It has been added as a new feature in the 3.1M2 release, though: https://jira.springsource.org/browse/SPR-8205
Thanks to Mark Fisher for pointing this out.
精彩评论