最近在使用quartz實現任務的定時自動啓動過程中,學到了不少知識。同時,也遇到了不少問題。在此,總結一下,以便自己或學習quartz的人在日後遇到類似問題時作爲參考。
1、 新建java項目(web項目也可,只不過本文內容旨在教大家如何在spring中整合quartz)。
2、 所需jar文件:
3、 將所有jar文件加入buildpath(具體如何添加下面截圖,知道的直接忽略)。
4、 在項目src目錄下創建xml文件,名字可以根據自己喜好選擇。一般默認使用ApplicationContext.xml。文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>
5、 添加<bean>標籤,完成以下內容配置:
注意:
(1)在配置CronTriggerBean時需要注意,在spring3中是CronTriggerBean,而在spring4中變成了CronTriggerFactoryBean。
(2)在<Beans>中不能夠設置default-lazy-init="true",否則定時任務不觸發,如果不明確指明default-lazy-init的值,默認是false。
(3)在<Beans>中不能夠設置default-autowire="byName"的屬性,否則後臺會報org.springframework.beans.factory.BeanCreationException錯誤,這樣就不能通過Bean名稱自動注入,必須通過明確引用注入。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置job實例 -->
<bean id="testJob" class="com.malq.spring4.beans.TestJob" />
<bean id="testJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="testJob" />
<property name="targetMethod" value="execute" />
<property name="concurrent" value="false" />
<!-- 是否允許任務併發執行。當值爲false時,表示必須等到前一個線程處理完畢後纔再啓一個新的線程 -->
</bean>
<!-- trigger配置 -->
<bean id="testTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="testJobDetail" />
<property name="cronExpression" value="*/3 * * * * ?" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="testTrigger" />
</list>
</property>
<property name="autoStartup" value="true" />
</bean>
</beans>
6、 編寫TestJob類,並在xml中加入bean配置。注意他的id要和MethodInvokingJobDetailFactoryBean中targetObject的ref一樣,實際上他就是一個targetObject。
7、 在TestJob類中編寫一個方法,然後在內部編寫需要執行的事件,比如查詢數據庫;注意方法內部的方法名對應targetMethod的value值。
8、 另外,要想運行明顯看到效果,那就新建一個類,然後加入xml文件中。即添加一個<bean id=”XXX” class=”類路徑”/>,然後在類的main方法中編寫如下語句:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
你的類名 對象名 = ctx.getBean(“你在xml中配置的類的id”);
System.out.println(對象名);
只要運行該方法,項目去加載applicationContext.xml,就會啓動定時任務。
好了就是這麼簡單。