spring quartz 多次调用
早上测试程序的时候,发现项目下的定时任务quartz同一时刻有一个任务执行了两次,但是我清楚地记得原来是没有问题,很是懊恼。
第一步
检查配置文件,文件内有配置concurrent为false,理论上来讲应该可以防止job同时执行两次的问题。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 要调用的工作类 --> <bean id="xmlJob" class="com.all58.video.quartz.XmlJob"></bean> <!-- 可继续加新的任务 --> <!-- 要调用的工作类结束 --> <bean id="xmlJobTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 调用的类 --> <property name="targetObject"> <ref bean="xmlJob"/> </property> <!-- 调用类中的方法 --> <property name="targetMethod"> <value>work</value> </property> <property name="concurrent"> <value>false</value> </property> </bean> <!-- 定义调用对象和调用对象的方法 --> <bean id="xmlJobTaskDoTime" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="xmlJobTask"/> </property> <property name="cronExpression"> <value>0 0/2 * ? * *</value> </property> </bean> <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序,不需要实例化对象 --> <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="xmlJobTaskDoTime"/> </list> </property> </bean></beans>第二步
既然不是quartz配置的问题,那就往上一层代码找找看吧,忽然发现SSH项目中出现了ApplicationContext被连续两次注入的问题,但是我只是在web.xml进行了一次引用配置,不应该调用两次才对...
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml,classpath:job.xml</param-value></context-param>
理论上来讲应该没问题了吧,但是还是不可以,applicationContext加载两次可以说得过去,但是定时任务还是被同时执行了两次,因此我得出了结果,不是applicationContext.xml被加载了两次,而是web.xml被加载了两次,从而造成了以上的结果。
那我就去查,什么情况下会出现web.xml被多次加载?
原来是TOMCAT的配置文件server.xml配置不当引起的
请看下面这段配置就是错误的:
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <Context path="" docBase="D:\apache-tomcat-6.0.14\webapps\Server" debug="0" reloadable="true"/>tomcat的默认加载工程目录为tomcat\webapps\....,这就会造成加载一次Server项目下的web.xml 第一次注入
由于本地中的工程有很多,所以为了方便配置了默认启动项目,添加了上面蓝色的配置,造成了第二次注入
解决办法:
1.更改server.xml中appBase=""。再次启动项目,一切正常。
2.删除蓝色配置,将项目放到tomcat\webapps\ROOT中,以此来达到默认启动的效果。
暂时只发现这两种解决办法,如果大家还有什么其他的解决办法,欢迎留言