spring定时任务实现

tomcat spring定时功能

新建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 name="updateDB"
		class="org.springframework.scheduling.quartz.JobDetailBean">
		<property name="jobClass">
			<value>com.travelsky.channelconn.adapter.XiRuanHotels.RateAmountSync</value>
		</property>
               <property name="jobDataAsMap">
                <MAP>
                     <ENTRY key="readXmlService ">
                            <REF bean="readXmlService"></REF>
                      </ENTRY> 
                </MAP>
         </property> 
	</bean>
    <bean id="XiRuanCronTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="updateDB" />
		</property>
		<property name="cronExpression">
			<!-- 每天15:49分取数据 -->
			<value>0 49 15 * * ?</value>
		</property>
	</bean>
	<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
	<property name="triggers"> 
	<ref local="XiRuanCronTrigger"></ref> 
	</property>
	</bean>
</beans>


<map>结点,这里主要是为了在定时任务需要使用到Bean,通过 Spring给注入进来,如果不写明,就会报
java.lang.NullPointerException错误,主要是因为没有注入Bean


将该xml加入到web的加载目录即可
<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:quartz.xml
			classpath:applicationMonitorContext.xml
		</param-value>
</context-param>


使用spring quartz功能
需要加入quartz,common-lang等四个JAR包

新建类实现接口QuartzJobBean的方法executeInternal

public class RateAmountSync extends  QuartzJobBean {

	public static String htlCode;
        private readXmlService readXmlService; 
	  @Override
	  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
	    // TODO Auto-generated method stub
		 if(Sync())
			 logger.info("同步信息成功");
		 else 
			 logger.info("同步价格失败");
	  }
}


注意:在Spring配置和 Quartz集成内容时,有两点需要注意
1、在<Beans>中不能够设置default-lazy-init="true",否则定时任务不触发,如果不明确指明default-lazy-init的值,默认是false。
2、在<Beans>中不能够设置 default-autowire="byName"的属性,否则后台会报 org.springframework.beans.factory.BeanCreationException错误,这样就不能通过Bean名称自动注入,必须通过明确引用注入。

你可能感兴趣的:(spring)