Two-Step walk:
(1). Two ways to implement the Javax.servlet.ServletContextListener Interface: contextinitialized () and contextdestroyed ()
Contextinitialized (): When the servlet container starts, it executes
Contextdestroyed (): When the servlet container stops, it executes
(2). Add a program in contextinitialized () that requires listening, and the Java.util.Timer schedule () method to control how often the listener executes
DEMO (This is one of my SMS reply to listen to the program prototype, streamlined a bit)
----------------------------------------------------------------
Replylistener.java
------------ ----------------------------------------------------
Package com.hanweb.jcms;
Import javax.servlet.*;
public class Replylistener implements Servletcontextlistener {
private replytimer RT = null;
public void cont Extinitialized (Servletcontextevent event) {
String status = [SYS] SMS reply listener start. "
Event.getservletcontext (). log (status);
System.out.println (status);
RT = new Replytimer (1);
Rt.start ();
}
public void contextdestroyed (Servletcontextevent event) {
String status = ' [SYS] SMS reply listener stop. ' ;
Event.getservletcontext (). log (status);
System.out.println (status);
if (rt!= null) {
Rt.stop ();
}
}
}
----------------------------------------------------------------
Replytimer.java
---------- ------------------------------------------------------
Package COM.HANWEB.JCMS
Import java.util.*;
public class Replytimer {
Private final timer timer = new timer (),
Private final int min
public replytim ER (int minutes) {
min = minutes;
}
public void Start () {
Date = new Date (),
Timer.schedule (New Replytask (), date, min * 1000);
}
public void Stop () {
Timer.cancel ();
}
}
----------------------------------------------------------------
Replytask.java
---------------- ------------------------------------------------
Package com.hanweb.jcms;
Import java.util.*;
public class Replytask extends TimerTask {
public void dosomething () {
System.out.println ("[SYS] SMS reply li Stener running ");
}
public void Run () {
dosomething ();
}
}
Put the compiled class file into the web-inf/classes and don't forget to add a listener statement to the web.xml of the current Web application in the servlet container:
<listener>
<listener-class>com.hanweb.jcms.ReplyListener</listener-class>
</listener>