作者:mobiledu2502918997 | 来源:互联网 | 2023-10-16 14:27
下面就Servlet侦听器结合Java定时器来讲述整个实现过程。要运用Servlet侦听器需要实现javax.servlet.ServletContextListener接口,同时实现它的con
下面就Servlet侦听器结合Java定时器来讲述整个实现过程。要运用Servlet侦听器需要实现
javax.servlet.ServletContextListener接口,同时实现它的contextInitialized和contextDestroyed两个接口函数。考虑定时器有个建立和销毁的过程,看了前面两个接口函数,就不容置疑的把建立的过程置入contextInitialized,把销毁的过程置入contextDestroyed了。我把ServletContextListener的实现类取名为ContextListener,在其内添加一个定时器,
示例代码如下所示:
package com.ganinfo.sc.cwe.user.util;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
/**
* 定时任务
* @author ruikanwang
*
*/
public class TimingListener extends HttpServlet implements ServletContextListener{
private static final long serialVersiOnUID= 1L;
private java.util.Timer timer = null;
@Override
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
@Override
public void contextInitialized(ServletContextEvent event) {
timer = new java.util.Timer(true);
event.getServletContext().log("获取app版本定时器已启动");
System.out.println("开始执行时间"+new Date());
timer.schedule(new ExTask(event.getServletContext()), 0, 5*60*1000);
event.getServletContext().log("已经添加任务调度表");
}
}
以上代码timer.schedule(new ExTask(event.getServletContext()), 0, 5*60*1000)这一行为定时器调度语句,其中ExTask是自定义需要被调度的执行任务
ExTask.java代码
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("开始执行指定任务");
String BASEURL=SystemConfig.getParam("APP_timing_version");
try {
doGetStr(BASEURL);
} catch (ParseException | IOException e) {
e.printStackTrace();
}
isRunning = false;
context.log("指定任务执行结束");
} else {
context.log("上一次任务执行还未结束");
}
}
}
做完上面这些我们只是完了一个个定时器的设定,如果想要在tomcat启动时就加载,必须要配置web.xml,
web.xml配置的内容如下
com.tjsoft.buisness.util.ContextListener
注意:
此监听器放在其他监听器后面防止读取不到配置文件情况