Java定时器(java.util.Timer)有定时触发计划任务的功能,通过配置定时器的间隔时间,在某一间隔时间段之后会自动有规律的调用预先所安排的计划任务(java.util.TimerTask)。另外,由于我们希望当Web工程启动时,定时器能自动开始计时,在整个Web工程的生命期里,定时器能在每晚深夜触发一次报表计算引擎。因此定时器的存放位置也值得考查,不能简单的存在于单个Servlet或JavaBean中,必须能让定时器宿主的存活期为整个Web工程生命期,在工程启动时能自动加载运行。结合这两点,跟Servlet上下文有关的侦听器就最合适不过了,通过在工程的配置文件中加以合理配置,会在工程启动时自动运行,并在整个工程生命期中处于监听状态。
......下面就Servlet侦听器结合Java定时器来讲述整个实现过程。要运用Servlet侦听器需要实现javax.servlet.ServletContextListener接口,同时实现它的contextInitialized(ServletContextEvent event)和contextDestroyed(ServletContextEvent event)两个接口函数。考虑定时器有个建立和销毁的过程,看了前面两个接口函数,就不容置疑的把建立的过程置入contextInitialized,把销毁的过程置入contextDestroyed了。
package com.derek.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import com.derek.pub.TimerManager;
/**
* 启动定时器的监听器
* @author derek
* @version 1.0
*/
public class TimerListener extends HttpServlet implements
ServletContextListener {
private TimerManager tm = null;
//Notification that the web module is ready to process requests
public void contextInitialized(ServletContextEvent sce) {
int day,hour,min,sec;
day = 26; hour = 16; min = 42; sec = 0;
tm = new TimerManager(day,hour,min,sec);
}
//Notification that the servlet context is about to be shut down
public void contextDestroyed(ServletContextEvent sce) {
tm.destoryTimer();
}
}
package com.derek.pub;
import java.util.Timer;
import java.util.Date;
import java.util.Calendar;
/**
* 定时器
* @author derek
* @version 1.0
*/
public class TimerManager {
Timer t = null;
public TimerManager(int day,int hour,int min,int sec) {
time(day,hour,min,sec);
}
public void time(int day,int hour,int min,int sec){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH,day);
c.set(Calendar.HOUR_OF_DAY,hour);
c.set(Calendar.MINUTE,min);
c.set(Calendar.SECOND,sec);
Date date = c.getTime();
System.out.println(c.getTime());
t= new Timer();
MyTask mt = new MyTask();
t.schedule(mt,date);
}
public void destoryTimer(){
t.cancel();
}
}
package com.derek.pub;
import java.util.TimerTask;
/**
* 计划任务代码
* @author derek
* @version 1.0
*/
public class MyTask extends TimerTask{
public MyTask() {
}
/**
* 任务块
*/
public void run() {
System.out.println("定时器RUN");
}
}
posted on 2006-04-26 16:52
Derek.Guo 阅读(2919)
评论(0) 编辑 收藏 所属分类:
Java