天天看點

spring 定時器執行兩次

spring錯誤筆記

spring定時器執行兩次因為導入了兩次

關于配置檔案如下 

<bean id="timeTaskService" class="xx.xxx.xxx.xxx.service.impl.na.TimeTaskService"/>

<task:scheduled-tasks scheduler="myScheduler"><!--30秒執行一次 -->

<task:scheduled ref="timeTaskService" method="checkHeartBeat" cron="0/30 * * * * ?"/>

</task:scheduled-tasks>

<task:scheduler id="myScheduler"/>

對應的類有個定時執行檢查的動作,但是動作中的日志每次輸出兩遍,一開始以為是log4j的輸出導緻的兩條,找了半天沒辦法還是決定eclipse調試列印一下,輸出竟然是兩條,那麼等于這個方法竟然執行了兩次。

根絕網上提供的說法如果導入兩次那麼就可能出現這種情況,發現真的是因為導入了兩次,因為在spring.xml中import中寫的

<import resource="classpath*:configspring*.xml"/>

而其他的包裡面還包含了相同的spring.xml檔案,且這個spring.xml還有這麼一個導入<import resource="spring-job.xml" />

等于加載了不止一遍,上邊導入的時候已經有了一個spring*.xml(可能也包含spring-job.xml了)而另一個又import了一次。

這個時候隻要把spring.xml中import導入寫成<import resource="classpath*:configspring.xml"/>隻導入spring.xml或者把另一個spring.xml中<import resource="spring-job.xml" />去掉即可。