How to set Server Time for ScheduledTimerTask in spring?
We are using ScheduledTimerTask to manage the jobs(automatic) in our application.We are using the following code:
<bean id="SampleTask" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject" ref="sampleScheduler" /> <property name="targetMethod" value="runMethod" /> </bean> <bean id="sampleScheduler" class="com.sample.SampleScheduler" /> <bean id="timerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask" ref="schedulerTask" /> <property name="delay" value="1000" /> <property name="period" value="60000" /> </bean> <bean class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref local="timerTask" /> </list> </property> </bean>
By using the above code runMethod is working fine for every one minute.But we would like to change the execution based on server time.For example,If time in server is 6 PM then we need to invoke the function.How to achieve it?
Help would be appreciated.
You can use task trigger of Spring to invoke at a certian time period, you can use CronTrigger.
Detailed documentation is here
If you have to use only ScheduledTimerTask, then invoke the timer task once a minute. Now from within the timer task, check if the time is 6AM and run the necessary functionality. Else return.
Con: This task which is NO-OP will get executed for every minute(except for once it has to do some processing.
Invoke the TimeTask only once from the spring. When the task is executed, you can get the current time and can compute the difference between current time and time to execute the actual task. (let this difference be called DELAY).
Now from with in this timer task, start a new Executor Executors.newScheduledThreadPool(1) and scheduleAtFixedRate with intial delay = DELAY and set the period as 1 day