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.TimeListener</listener-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("===============定时任务方法开始执行====");
     }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值