主要是用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())); } }