Spring集成Quartz實現定時器

利用Spring集成Quartz能夠輕鬆實現一個定時器,其中Quartz的配置applicationContext-quartz.xml以下:java

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
	default-lazy-init="true">

	<description>Quartz的本地Cron式執行任務配置</description>

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="autoStartup"><value>true</value></property>
		<property name="triggers">
			<list>
				<ref local="scheduleFactoryTrigger"/>
			</list>
		</property>
	</bean>
	
	<bean id="scheduleFactoryTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail"><ref bean="scheduleFactory" /></property>
		<property name="cronExpression">
			<value>0 35 10 * * ?</value>
		</property>
	</bean>
	
	<bean id="schedule" class="要執行的方法所在類的全路徑"></bean>
	
	<bean id="scheduleFactory" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject"><ref bean="schedule" /></property>
		<property name="targetMethod"><value>execute</value></property><!--執行execute方法-->
		<property name="concurrent" value="false" />
	</bean>

</beans>

其中cronExpression能夠根據本身的須要配置執行方法的時間,具體配置能夠參考cronExpression語法詳解。web

而後須要在配置文件web.xml中添加對Quartz的引用,保證當服務器啓動的時候,計時器就會生效。添加以下:spring

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath*:/applicationContext-quartz.xml,
		</param-value>
	</context-param>
相關文章
相關標籤/搜索