下面就Servlet侦听器结合Java定时器来讲述整个实现过程。要运用Servlet侦听器需要实现
javax.servlet.ServletContextListener接口,同时实现它的contextInitialized (ServletContextEvent event)和contextDestroyed(ServletContextEvent event)两个接口函数。考虑定时器有个建立和销毁的过程,看了前面两个接口函数,就不容置疑的把建立的过程置入 contextInitialized,把销毁的过程置入contextDestroyed了。
我把ServletContextListener的实现类取名为ContextListener,在其内添加一个定时器,示例代码如下所示:
package com.tjsoft.buisness.util;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
public class ContextListener extends HttpServlet implements
ServletContextListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public ContextListener() {
}
private java.util.Timer timer = null;
public void contextInitialized(ServletContextEvent event) {
timer = new java.util.Timer(true);
event.getServletContext().log("定时器已启动");
timer.schedule(new ExTask(event.getServletContext()), 0, 1000*10*5);
event.getServletContext().log("已经添加任务调度表");
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
}
以上代码timer.schedule(new ExTask(event.getServletContext()), 0, 60*60*1000)这一行为定时器调度语句,其中ExTask是自定义需要被调度的执行任务
ExTask.java代码
package com.tjsoft.buisness.util;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import com.tjsoft.buisness.action.ExAction;
public class ExTask extends TimerTask {
private static boolean isRunning = false;
private ServletContext context = null;
public ExTask(ServletContext context) {
this.context = context;
}
@Override
public void run() {
if (!isRunning) {
isRunning = true;
context.log("开始执行指定任务");
new ExAction().exDate();//这个位子就是你要定时的程序的入口.
isRunning = false;
context.log("指定任务执行结束");
} else {
context.log("上一次任务执行还未结束");
}
}
}
做完上面这些我们只是完了一个个定时器的设定,如果想要在tomcat启动时就加载,必须要配置web.xml还不够,
web.xml配置的内容如下
<listener>
<listener-class>com.tjsoft.buisness.util.ContextListener</listener-class>
</listener>
以上为个人在项目中所得,忘与各们共同进步O(∩_∩)O