主要是用Sping来配置定时触发任务函数,本质也是Java的TimerTask:
首先定义一个计时器配置文件:
### schedulingContext-timer.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!-- ======================================================================= -->
<!-- 缓存配置文件 -->
<!-- @author linshutao -->
<!-- CleanEntryEventCacheTask: 执行任务的类 delay: 延迟执行 period:刷新间隔 -->
<!-- ======================================================================= -->
<beans>
<bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref local="MyScheduledTimerTask" />
</list>
</property>
</bean>
<bean id="CleanEntryEventCacheTask" class="com.syni.im800.kb.auto.service.KbsCleanEntryEventCache">
</bean>
<bean id="MyScheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="CleanEntryEventCacheTask" />
</property>
<property name="delay">
<value>10000</value>
</property>
<property name="period">
<value>60000</value>
</property>
</bean>
</beans>然后再web.xml中配置,读取该文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-*.xml,
/WEB-INF/schedulingContext-timer.xml,
/WEB-INF/schedule-context.xml,
classpath*:com/syni/im800/kb/auto/dao/applicationContext-hibernate.xml,
classpath*:com/syni/im800/kb/auto/service/applicationContext-service.xml,
classpath*:com/syni/im800/kb/auto/service/applicationContext-mail.xml,
/WEB-INF/security/security.xml
</param-value>
</context-param>
因为已经配置了加载文件内容的servlet,所以上面的/WEB-INF/schedulingContext-timer.xml,就可以直接添加进去,如果你的web.xml还没配置,那么可以用
org.springframework.web.context.ContextLoaderServlet,
3.0中把这个删掉了,你也可以用
Spring3.0下可以采用另外两种启动方式:ContextLoaderListener和ContextLoaderPlugIn。建议使用ContextLoaderListener,具体实现就是在web.xml中添加:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>最后是我的任务类:
/**
* 清除显示条目相关事件(编辑中,被退回,审核中等等)的缓存
* @author linshutao
* 2011年8月11日 14:43:33
* */
package com.syni.im800.kb.auto.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.syni.im800.kb.attendant.webapp.action.AttendantLoginAction;
import com.syni.im800.kb.common.CacheManager;
public class KbsCleanEntryEventCache extends java.util.TimerTask{
private static final Log log = LogFactory.getLog(KbsCleanEntryEventCache.class);
public void run() {
log.debug("#############清除显示条目相关事件的缓存...");
CacheManager cacheManager = CacheManager.getInstance();
cacheManager.clearAll();
}
}

本文介绍如何使用Spring框架配置定时任务,通过定义计时器配置文件schedulingContext-timer.xml,并在web.xml中进行配置,实现缓存清理任务的自动执行。
572

被折叠的 条评论
为什么被折叠?



