java web 项目中定时器的写法

在java web项目中,有时我们需要在一个规定的时间内执行相应的操作,例如:中国移动会在每个月的最后一天的凌晨清除用户的剩余流量,一些项目中会在每个月的25号统计公司员工的绩效等,这个时候就需要用到定时器。
使用工具:
1. java 的 concurrent包下的Timer
2. java 的 concurrent包下TimerTask类
3. 监听器(Listener)
设计步骤
1. 编写实体类继承TimerTask类,并重写其run()方法,将要定时执行的任务写在run()方法里(attention :TimerTask is a
abstract class);
2. 设计一个监听器,在其contextInitialized()方法里新建Timer类,并调用其Timer.schedule(TimerTask task, Date time) 方法,
在监听的contextDestroyed()方法中调用timer.cancel()方法在项目关闭时销毁定时器;
3. 在web.xml文件中注册相应的监听器。

监听器类

package sample.hello.resources;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TimeListener implements ServletContextListener{

 private Timer timer = null;

 public TimeListener() {
  // TODO Auto-generated constructor stub
 }
 @Override
 public void contextDestroyed(ServletContextEvent arg0) {
  // TODO Auto-generated method stub
        timer.cancel();  
        arg0.getServletContext().log("定时器销毁"); 
 }
 @Override
 public void contextInitialized(ServletContextEvent arg0) {
  // TODO Auto-generated method stub

        /** 
         * 设置一个定时器 
         */  
        timer = new Timer(true);  

        arg0.getServletContext().log("定时器已启动");  

        /** 
         * 定时器到指定的时间时,执行某个操作(如某个类,或方法) 
         */  
        //后边最后一个参数代表监视器的监视周期  
        timer.schedule(new AppTimeTask(arg0.getServletContext()), 0, 5000);  

        arg0.getServletContext().log("已经添加任务调度表"); 
 }
}

在使用监听器之前记得在web.xml文件中注册此监听器

<listener>  
        <listener-class>sample.hello.resources.TimeListenerlistener-class>  
listener>

定时任务代码

package sample.hello.resources;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class AppTimeTask extends TimerTask {
     private ServletContext context = null;
     public AppTimeTask() {
          super();
     }

     public AppTimeTask(ServletContext context) {
          this.context = context;
     }


     @Override
     public void run() {
      // TODO Auto-generated method stub
                      *//** 
                     * 此处写执行任务代码 
                     *//*  
                    System.out.println("===============定时任务方法开始执行====");
     }

}

你可能感兴趣的:(java-web)