這種方式是純粹的java代碼,須要繼承timerTask接口並重寫run方法,建立這個類的時候就會調用run方法。
基本的使用邏輯是:
把本身須要處理的業務邏輯放在本身寫的這個繼承了timerTask的類中,而後new一個timer並調用schedule方法,在schedule中設定一個新的本身類的對象爲參數,同時配置其餘時間信息,示例以下:
package scheduleTest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class scheduleTest2 implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
/**
* 啓動項目的時候調用
* @author:tuzongxun
* @Title: contextInitialized
* @Description: TODO
* @param @param arg0
* @date Jun 3, 2016 12:33:36 PM
* @throws
*/
public void contextInitialized(ServletContextEvent arg0) {
this.startTask();
}
/**
* 啓動方法
*
* @author:tuzongxun
* @Title: startTask
* @param
* @return void
* @date Jun 3, 2016 12:34:23 PM
* @throws
*/
public void startTask() {
Timer timer = new Timer();
timer.schedule(new Sche(), 0, 5000);
}
/**
* 定時器類
*
* @author tuzongxun123
*
*/
class Sche extends TimerTask {
@Override
public void run() {
Date date = new Date();
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sim.format(date);
System.out.println("這是java定時器3,每五秒執行一次,當前時間:" + dateStr);
}
}
}
上邊的代碼中
Sche類即本身所寫的定時任務類,我是之內部類的方式聲明。
以後在外部類scheduleTest2的startTask方法中調用定時任務,每五秒執行一次。
由於僅僅是這樣的話,程序啓動時並不能觸發我這個類,不能自動調用startTask方法,所以便讓外部類實現了
ServletContextListener 監聽器的接口,同時重寫contextInitialized這個方法,以便於在web.xml中配置,讓程序啓動時便調用運行這個定時任務。
所以對應的web.xml代碼便更改爲下邊的樣子:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>appversion</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring2.xml</param-value>
</context-param>
<listener>
<description>spring監聽器</description>
<listener-class>scheduleTest.scheduleTest2</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
要說明如下的是,這裏的spring2.xml在本示例中沒有實質性的做用,只由於這個web程序須要一個初始加載文件,即原來的
ApplicationContext.xml,所以這裏就配置了一個除開開頭和結尾什麼都沒有的文件,以下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">
</beans>