Spring可以用IOC的方式配置Quartz,就如同配置TimerTask一样方便
job:
package ch14.SpringAndQuartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class QuartzJob implements Job ...{

public void execute(JobExecutionContext context) throws JobExecutionException ...{
System.out.println(context.getFireTime());
System.out.println("this is a message");
}
}
配置文件:
<?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-2.0.xsd">
<bean id="job" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass"><!-- 此处需要一个string类型的类名 -->
<value>ch14.SpringAndQuartz.QuartzJob</value>
</property>
<!-- 如果存在JobDataMap,则进行如下配置
<property name="jobDataAsMap">
<map>
<entry key="message">
<value>this is a message</value>
</entry>
</map>
</property>
-->
</bean>
<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="job"/>
</property>
<property name="cronExpression">
<value>2/5 * 23 ? 9 3</value>
</property>
</bean>
<bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<ref bean="trigger"/>
</property>
</bean>
<bean id="jobClass" class="ch14.SpringAndQuartz.QuartzJob"></bean>
</beans>
package ch14.SpringAndQuartz;
import java.util.Date;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestQuartz ...{

public static void main(String[] args) throws Exception ...{
ApplicationContext context=new ClassPathXmlApplicationContext("ch14/SpringAndQuartz/applicationContext.xml");
System.in.read();
}
}
运行结果
Tue Sep 11 23:19:02 CST 2007
this is a message
Tue Sep 11 23:19:07 CST 2007
this is a message
本文展示了一个使用Spring框架配置Quartz任务调度器的例子。通过XML配置文件定义了一个定时任务,该任务每5分钟的第2秒触发并执行打印当前时间及消息的操作。
1339

被折叠的 条评论
为什么被折叠?



