1.导入spring相关的jar包、spring-context-support-4.0.8.RELEASE.jar、quartz-2.2.1.jar
2、在Spring中使用Quartz有两种方式实现:第一种是任务类继承QuartzJobBean,第二种则是在配置文件里定义任务类和要执行的方法,类和方法仍然是普通类。很显然,第二种方式远比第一种方式来的灵活。
第一种方式的JAVA代码:
public class CarPositionJob extends QuartzJobBean {
private CarPositionService postionService;
@Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
// TODO Auto-generated method stub */30 * * * * ?
postionService.doCarPositionUpLoad();//将车辆位置信息查询出来插入任务表
}
//
/**
* @param postionService the postionService to set
*/
public void setPostionService(CarPositionService postionService) {
this.postionService = postionService;
}
}
Spring的配置文件:创建quartz.xml 文件,具体配置
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
<!--startProjectBeans-->
<bean id="CarPositionService" class="com.dfhc.bus.carposition.service.CarPositionService"> </bean>
<!-- For times when you need more complex processing, passing data to the scheduled job 任务jo配置-->
<bean name="carPostion" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.dfhc.pub.web.CarPositionJob" />
<property name="jobDataMap">
<map>
<entry key="postionService" value-ref="CarPositionService" />
</map>
</property>
<property name="durability" value="true" />
</bean>
<!-- Run the job every 30 seconds quartz配置任务调用 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="carPostion" />
<property name="cronExpression" value="*/30 * * * * ?" />
</bean>
<!-- Scheduler factory bean to glue together jobDetails and triggers to Configure Quartz Scheduler 启动调度任务 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="carPostion" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
</beans>