定時任務@schedule開啟兩次問題解決
阿新 • • 發佈:2018-12-01
1,定時任務
定時任務有三種實現方式,java的timer類,spring框架,quartz外掛。
在Spring框架中,實現定時任務很簡單。常用的實現方式是使用註解@Schedule。
public class Scheduler{ @Scheduled(cron = "0 0 3 * * ?") public void demoSchedule() { doWork(); } }
然後在spring配置檔案中加上掃描開關
<task:annotation-driven/>
2,定時任務開啟兩次
發現定時任務總是執行兩次,按照網上的說法,把context中的app設定為空之類的啥,反正試了沒效果!
我的解決方法是,單獨使用配置檔案spring-schedule.xml配置任務。
/進行定時任務的類,將其定義為一個bean <bean id="test" class="com.service.TestImplel"></bean> //通過task標籤,定義定時功能 <task:scheduled-tasks> <task:scheduled ref="test" method="doWork" cron="0 0/5 ** * ?" /> </task:scheduled-tasks>
分析載入兩次原因是xml初始化一次,註解掃描一次,所以載入兩次,只要把註解單獨配置,指定啟動一次即可解決該問題。