主要是用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> <!-- Spring --> <bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <!-- 对应本身配置定时器参数的ID --> <ref local="MyScheduledTimerTask" /> </list> </property> </bean> <!-- 对应本身写的TimerTask类路径--> <bean id="CleanEntryEventCacheTask" class="com.baosight.wrms.util.TimerTaskUtil"> </bean> <!-- 配置定时器参数 --> <bean id="MyScheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask"> <!--注入TimerTask类 --> <ref bean="CleanEntryEventCacheTask" /> </property> <!--服务器启动后 延时10s 执行任务 --> <property name="delay"> <value>10000</value> </property> <!-- 服务器启动后 60s 执行任务一次 --> <property name="period"> <value>60000</value> </property> </bean> </beans> 而后再web.xml中配置,读取该文件 <context-param> <param-name>contextConfigLocation</param-name> <param-value> <!-- Timer XML存放路径 --> /WEB-INF/framework/Timer/schedulingContext-timer.xml, <!--项目中的全部spring 路径 --> classpath*:spring/**/applicationContext.xml, classpath*:spring/**/applicationContext*.xml</param-value> </context-param> java代码 package com.baosight.wrms.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimerTask; public class TimerTaskUtil extends TimerTask { @Override public void run() { // TODO Auto-generated method stub SimpleDateFormat simpleDateFormat=null; simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); System.out.println("当前的系统时间为:"+simpleDateFormat.format(new Date())); } }