最近在使用quartz实现任务的定时自动启动过程中,学到了不少知识。同时,也遇到了不少问题。在此,总结一下,以便自己或学习quartz的人在日后遇到类似问题时作为参考。
1、 新建java项目(web项目也可,只不过本文内容旨在教大家如何在spring中整合quartz)。
2、 所需jar文件:
3、 将所有jar文件加入buildpath(具体如何添加下面截图,知道的直接忽略)。
4、 在项目src目录下创建xml文件,名字可以根据自己喜好选择。一般默认使用ApplicationContext.xml。文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>
5、 添加<bean>标签,完成以下内容配置:
注意:
(1)在配置CronTriggerBean时需要注意,在spring3中是CronTriggerBean,而在spring4中变成了CronTriggerFactoryBean。
(2)在<Beans>中不能够设置default-lazy-init="true",否则定时任务不触发,如果不明确指明default-lazy-init的值,默认是false。
(3)在<Beans>中不能够设置default-autowire="byName"的属性,否则后台会报org.springframework.beans.factory.BeanCreationException错误,这样就不能通过Bean名称自动注入,必须通过明确引用注入。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置job实例 -->
<bean id="testJob" class="com.malq.spring4.beans.TestJob" />
<bean id="testJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="testJob" />
<property name="targetMethod" value="execute" />
<property name="concurrent" value="false" />
<!-- 是否允许任务并发执行。当值为false时,表示必须等到前一个线程处理完毕后才再启一个新的线程 -->
</bean>
<!-- trigger配置 -->
<bean id="testTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="testJobDetail" />
<property name="cronExpression" value="*/3 * * * * ?" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="testTrigger" />
</list>
</property>
<property name="autoStartup" value="true" />
</bean>
</beans>
6、 编写TestJob类,并在xml中加入bean配置。注意他的id要和MethodInvokingJobDetailFactoryBean中targetObject的ref一样,实际上他就是一个targetObject。
7、 在TestJob类中编写一个方法,然后在内部编写需要执行的事件,比如查询数据库;注意方法内部的方法名对应targetMethod的value值。
8、 另外,要想运行明显看到效果,那就新建一个类,然后加入xml文件中。即添加一个<bean id=”XXX” class=”类路径”/>,然后在类的main方法中编写如下语句:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
你的类名 对象名 = ctx.getBean(“你在xml中配置的类的id”);
System.out.println(对象名);
只要运行该方法,项目去加载applicationContext.xml,就会启动定时任务。
好了就是这么简单。