http://apps.hi.baidu.com/share/detail/33720498 (各种定时器)
本文主要使用 Spring ,Quartz 来简单的实现一个定点执行的定时任务。
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,可以用来创建简单或者复杂的定时任务。
l Timer方式实现定时器,原理简单,实现方便,在执行简单的任务比较方便,不足之处是无法确定执行时间,并且依赖性比较强,必须继承指定的类.
l Quartz方式实现定时器,方便,清晰指定启动时间,定时参数比较灵活,容易实现比较复杂的定时任务,不足之处是需要实现特定接口,加载其框架
两种方式各有优缺点,在特定场合可以根据其特点选择使用。
Spring定时任务对Timer与Quartz都提供了支持,并且实现步骤基本一样
下面是一个Spring Quartz 实例:
一.创建一个定时任务类:HKHotelSourceMapJob
<!--EndFragment-->
public class HKHotelSourceMapJob {
protected static Log log = LogFactory.getLog(HKHotelSourceMapJob.class);
private HotelSourceMapFacade hotelSourceMapFacade;
public void run() {
Set<String> allHotelSourceMap = hotelSourceMapFacade.getAllHotelSourceMap(); //查询本地配置的所有映射关系
Set<String> hkRoomKindSet = hotelSourceMapFacade.getHkRoomKind(new Date(), new Date()); // 查询中旅酒店当天的有效房型
updateHotelSourceMapSet(hkRoomKindSet, "Y");//有效房型
log.info(new Date() + "有效的房型:"+ hkRoomKindSet);
allHotelSourceMap.removeAll(hkRoomKindSet); //所有映射 - 有效房型映射 = 无效房型映射
updateHotelSourceMapSet(allHotelSourceMap, "N");//无效房型
log.info(new Date() + "有效的房型:"+ allHotelSourceMap);
}
}
二.定义一个Spring 配置文件 appContext-assistant-Timer.xml :
<!--EndFragment-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 中旅同步映射定时器 start -->
<bean id="hkHotelSourceMapFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="hkHotelSourceMapJobTrigger" />
</list>
</property>
</bean>
<bean id="hkHotelSourceMapJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="hkHotelSourceMapJobDetail">
</property>
<property name="cronExpression">
<!--每天2点10分,11点10分触发 -->
<value>0 10 2,16 * * ?</value>
</property>
</bean>
<bean id="hkHotelSourceMapJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="hkHotelSourceMapJob" />
<property name="targetMethod" value="run" />
</bean>
<!-- 中旅同步映射定时器 end -->
<bean id="hkHotelSourceMapJob" class="com.ctol.mango.pge.common.HKHotelSourceMapJob">
<property name="hotelSourceMapFacade" ref="hotelSourceMapFacade" />
</bean>
</beans>
三.让容器启动时自动加载配置文件 appContext-assistant-Timer.xml:
在web.xml 中加入:
<!--EndFragment--><context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/conf/spring/appContext-assistant-Timer.xml
.....(其他需要加载的配置文件,已逗号分隔)
</param-value>
</context-param>
通过以上3个步骤就完成了一个简单的定时任务, 在每天的2点10分,16点10分定时同步数据。
<!--EndFragment-->
<!--EndFragment--> <!--EndFragment-->
<!--EndFragment-->
<!--EndFragment-->