In Web applications, sometimes customers need timed programs that do not require the customer to operate on their own, but are triggered by the application to perform certain actions on their own. This time, the use of monitoring and timer can basically achieve this requirement.
1. Create a listening Servelet, this class inherits Javax.servlet.http.HttpServlet and implements Javax.servlet.ServletContextListener.
[HTML]View PlainCopy
- Package com.bndz.outMail;
- Import Java.util.Timer;
- Import javax.servlet.ServletContextEvent;
- Import Javax.servlet.ServletContextListener;
- Import Javax.servlet.http.HttpServlet;
- /**
- *
- * Files sent by the listener need to be configured in Web-xml
- */
- public class Mailsendlistener extends HttpServlet implements
- Servletcontextlistener {
- /**
- * Monitoring begins to destroy
- */
- public void contextdestroyed (Servletcontextevent sce) {
- }
- /**
- * Monitoring starts execution
- */
- public void contextinitialized (Servletcontextevent sce) {
- When the listener starts executing, set a time
- Timer timer = new timer ();
- System.out.println ("-------MailSend timer begins execution--------------");
- Mailsendtask msendtask = new Mailsendtask ();
- Timer.schedule (Msendtask, 60 * 1000, 10 * 1000);
- System.out.println ("-------MailSend timer is already executing--------------");
- }
- }
2. Configure the Web. xml file for configuration.
[HTML]View PlainCopy
- <listener>
- <listener-class>com.bndz.outmail.mailsendlistener</listener-class>
- </Listener>
3. Create a mailsendtask, inherit the Java.util.TimerTask, and execute the program within the Run method.
[HTML]View PlainCopy
- Package com.bndz.outMail;
- Import Java.util.Date;
- Import Java.util.TimerTask;
- /**
- * JAVA a timed task
- *
- * @author guox2011-05-10
- *
- */
- public class Mailsendtask extends TimerTask {
- Public Mailsendtask () {
- }
- /**
- * The Run method is put into a schedule when executing a timed program to perform the import
- */
- public void Run () {
- System.out.println (New Date () + "---mailsendtask begin to RUN------------");
- Mailsendmanager Mainsendmanager = new Mailsendmanager ();
- Mainsendmanager.waitingmailremind ();
- }
- }
4. In the Contextinitialized method of listening for Servelet, write a timer, and let it schedule method to perform the Mailsendtask task described above.
[HTML]View PlainCopy
- When the listener starts executing, set a time
- Timer timer = new timer ();
- System.out.println ("-------MailSend timer begins execution--------------");
- Mailsendtask msendtask = new Mailsendtask ();
- Timer.schedule (Msendtask, 60 * 1000, 10 * 1000);
- System.out.println ("-------MailSend timer is already executing--------------");
Servlet Listener and Timer timer for Java Web application simple automatic job