I'm setting up a scheduled tasks scheme in spring, using the task namespace.
I want to schedule most tasks to fire according to a cron expression, and some to fire just once, a fixed delay after startup, and then never again (i.e. what setting repeatCount to 0 on a SimpleTriggerBean would achieve).
Is it possible to achieve this within the task namespace, or do I need to revert to defining beans for my triggers?
Java Cron ExpressionThe @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. The @Scheduled annotation is used to trigger the scheduler for a specific time period.
The default scheduler pool size in spring-boot is only one.
If you don't need an initial delay, you can make it run 'just once' on startup as follows:
<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>
(Of course, if you think your code is going to run for longer than 3E8 years, you may need a different approach...)
If you need an initial delay, you can configure it as follows (I'm testing with Spring 3.1.1) - this doesn't require any additional dependencies and you don't have to write your own trigger, but you do have to configure the PeriodicTrigger provided by Spring:
<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> 
Spring 3.2 appears to support the "initial-delay" attribute directly, but I haven't tested this; I'd guess this works:
<task:scheduled-tasks>
    <task:scheduled ref="myThing" method="doStuff" 
                        fixed-rate="#{ T(java.lang.Long).MAX_VALUE }" 
                        initial-delay="5000"/>
</task:scheduled-tasks>
                        My working example:
<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>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With