Spring整合Quartz示例

Spring版本:3.2.9.RELEASE

Quartz版本:2.2.1

Job.java:

package com.sean;

import org.apache.log4j.Logger;

public class Job {
	private static Logger log = Logger.getLogger("MyJob");
	
	public void run(){
		log.info("This is just a test!");
	}
}

applicationContext.xml:

<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
		"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="job" class="com.sean.Job" >
	</bean>
	<!-- MethodInvokingJobDetailFactoryBean用来将一个Spring bean包装为一个job -->
	<!-- 使用MethodInvokingJobDetailFactoryBean包装的job不能被序列化 --> 
	<bean id="myJobDetail" 
			class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<!-- 被包装的Spring bean -->
		<property name="targetObject" ref="job" />
		<!-- job执行方法 -->
		<property name="targetMethod" value="run" />
		<!-- 无状态job -->
		<property name="concurrent" value="false" />
	</bean>
	<bean id="myCronTrigger" 
			class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="myJobDetail" />
		<property name="cronExpression">
			<value>0/10 * * * * ?</value>
		</property>
	</bean>
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="myCronTrigger" />
			</list>
		</property>
	</bean>
</beans>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://java.sun.com/xml/ns/javaee" 
		xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
		xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
				http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
		id="WebApp_ID" version="2.5">
  <display-name>test</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:applicationContext.xml
		</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/log4j.properties</param-value>
	</context-param>
	
	<listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
	
	<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

log4j.properties:

log4j.rootLogger=info,default

log4j.appender.default=org.apache.log4j.ConsoleAppender
log4j.appender.default.layout=org.apache.log4j.PatternLayout
log4j.appender.default.layout.ConversionPattern=%d{[MM-dd HH:mm:ss]}->%m%n

log4j.logger.MyJob=info,MyJob    
log4j.appender.MyJob=org.apache.log4j.RollingFileAppender     
log4j.additivity.MyJob=false    
log4j.appender.MyJob.File=/log/MyJob.log    
log4j.appender.MyJob.MaxFileSize=10MB    
log4j.appender.MyJob.MaxBackupIndex=0    
log4j.appender.MyJob.layout=org.apache.log4j.PatternLayout    
log4j.appender.MyJob.layout.ConversionPattern=%d{MM-dd HH:mm:ss}->%m%n

你可能感兴趣的:(spring,quartz)