I have a simple TimerTask implementation that just prints to the System.out
public class RefreshUserAndOLStatsJob extends TimerTask {
public void run() {
System.out.println("RefreshUserAndOLStatsJob running at: " + new Date(this.scheduledExecutionTime()));
}
}
It is configured in the Spring application context as follows
<bean id="refreshUserAndOLStatsTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<!-- run every 30 secs -->
<property name="period" value="30000" />
<property name="timerTask" ref="refreshUserAndOLStatsJob" />
</bean>
<bean class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref local="refreshUserAndOLStatsTask" />
</list>
</property>
</bean>
It is supposed to run every 30 seconds. Which it does but does so twice for each run, as is evident from the System out
RefreshUserAndOLStatsJob running at: Thu Feb 14 20:59:01 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 20:59:02 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 20:59:31 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 20:59:32 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:00:01 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:00:02 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:00:31 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:00:32 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:01:01 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:01:02 IST 2013
RefreshUserAndOLStatsJob running at: Thu Feb 14 21:01:31 IST 2013
Can someone guess why it could be so.
EDIT 1 : I am on Tomcat7
EDIT 2 : On adding the hashCode, as suspected by Matt, there are 2 separate instances of RefreshUserAndOLStatsJob. It seems that the application context IS indeed being initialized twice.
As for the initialization of refreshUserAndOLStatsJob in application context xml, it is not explicitly declared, but because RefreshUserAndOLStatsJob is a class marked as @Component, it seems Spring can load it automatically.
TimerFactoryBeanin your application context? Do you know if the context get loaded multiple times? Where is therefreshUserAndOLStatsJobbean initialized?System.out.println(hashCode());to your task's run method to see if it's the sameRefreshUserAndOLStatsJobobject or two separate ones. Assuming you haven't overriddenhashCode, it'll execute theObjectimplementation which should be different for two separate objects.