Java中用ServletListener实现定时监听
分两步:
(1)实现javax . servlet . servletcontextlistener接口的两个方法:contextInitialized()和context destroyed()
context initialized():启动Servlet容器时会执行context destroyed();
将在Servlet容器停止时执行;(2)在contextInitialized()中添加要监控的程序,test,建议java.util.Timer的schedule()方法控制监听器执行的频率
DEMO(这是我的短信回复监控程序的一个原型,是简化的)
replylistener.java
package com . hanweb . jcms;
导入javax . servlet . *;
公共类ReplyListener实现ServletContextListener {
私有ReplyTimer rt = null
public void context initialized(ServletContextEvent事件){
String status = "[SYS] SMS回复侦听器启动,";
event.getServletContext()。日志(状态);
system . out . println(status);
rt = new reply timer(1);
rt . start();
}
public void context destroyed(ServletContextEvent事件){
String status = "[SYS] SMS回复侦听器停止,";
event.getServletContext()。日志(状态);
system . out . println(status);
if (rt!= null){
rt . stop();
}
}
}
reply timer . Java
包com . hanweb . jcms;
导入Java . util . *;
public类reply Timer {
private final Timer Timer = new Timer();
private final int min;
public reply timer(int minutes){
min = minutes;
}
public void start(){
Date Date = new Date();
timer . schedule(new reply task(),date,min * 60 * 1000);
}
public void stop(){
timer . cancel();
}
}
reply task . Java
包com . Han web . jcms;
导入Java . util . *;
public class ReplyTask扩展TimerTask {
public void do something(){
system . out . println("[SYS]SMS回复侦听器运行");
}
public void run(){
do something();
}
}
把编译好的类文件放到WEB-INF/classes中,考一考。大注意,别忘了在Servlet容器中的当前web应用的web.xml中添加一条监听语句:
com . hanweb . jcms . reply listener[
0条评论