Fightingcjj 2012-07-30
1.环境Spring3.1,Quartz1.6.0(经测试Spring不支持最新的Quartz2.x)
2.spring提供了创建调度任务的对应的Bean,首先加载调度任务的配置文件,web.xml中指定需加载的配置文件路径(例中Quartz的bean配置信息与其它bean不在同一个配置文件中):
<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/beans.xml /WEB-INF/Quartz.xml </param-value> </context-param>
注:通过监听器启动spring容器代码段:
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
调度配置文件Quartz.xml内容(以定时发送邮件操作为例):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 包含调度执行的方法 --> <bean id="sendMailJob" class="com.my.mailsend.quartz.SendMailJob" /> <!-- 调度任务详情 --> <bean id="sendMailJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 指定任务执行时调用的方法及所在类 --> <property name="targetObject"> <ref bean="sendMailJob"></ref> </property> <property name="targetMethod"> <value>doJob</value> </property> </bean> <!-- 触发器任务:指定调度任务、执行时间及频率 --> <bean id="sendMailTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="sendMailJobDetail"></ref> </property> <!-- 在属性文件中配置,格式为:email.send.cronExpression = 0 03/30 * * * ? --> <property name="cronExpression"> <value>${email.send.cronExpression}</value> </property> </bean> <!-- 调度任务列表:指定触发器任务列表 --> <bean id="quartz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="sendMailTrigger"></ref> </list> </property> </bean> </beans>
其中SendMailJob中的doJob方法代码如下(仅仅生成bo实例,执行具体的业务方法):
// 根据邮件发送任务列表进行邮件发送的任务调度方法 public void doJob() { WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); MailSendBo bo = (MailSendBo) wac.getBean("mailSendBo"); bo.doSendMail(); }