这种方式是纯粹的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>