我有一个简单的TimerTask实现,只是打印到System.out
public class RefreshUserAndOLStatsJob extends TimerTask {
public void run() {
System.out.println("RefreshUserAndOLStatsJob running at: " + new Date(this.scheduledExecutionTime()));
}
}
它在Spring应用程序上下文中配置如下
<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>
它应该每30秒运行一次。它的确如此,但每次运行都会这样做两次,从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
有人可以猜到为什么会如此。
编辑1:我在Tomcat7上
编辑2:在添加hashCode时,正如Matt所怀疑的那样,有2个单独的RefreshUserAndOLStatsJob实例。似乎应用程序上下文确实被初始化了两次。
至于应用程序上下文xml中的refreshUserAndOLStatsJob的初始化,它没有显式声明,但是因为RefreshUserAndOLStatsJob是一个标记为@Component的类,所以Spring似乎可以自动加载它。