码迷,mamicode.com
首页 > 编程语言 > 详细

Javaweb中的定时器

时间:2020-04-15 18:14:59      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:timertask   cal   cancel   code   pip   end   listen   mon   XML   

 

 

1.任务类

import java.util.TimerTask;
import javax.servlet.ServletContext;

public class MyTask extends TimerTask{
    private ServletContext context = null;
    
    public CleanTpIpTask(ServletContext servletContext) {
        this.context = servletContext;
    }

    @Override
    public void run() {
        //定时任务逻辑代码
    }

}

2.监听类

import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyTaskListener implements ServletContextListener {
    private java.util.Timer timer = null; 
    MyTask myTask = null;
    public void contextDestroyed(ServletContextEvent arg0) {
        timer.cancel();
        
    }
    public void contextInitialized(ServletContextEvent arg0) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        c.set(year, month, day, 3, 0, 0);//项目启动当天凌晨3点执行1次,如果已经超过凌晨3点,立刻执行
        Date date = c.getTime();
        timer = new java.util.Timer(true); 
        
        int period = 24 * 60 * 60 * 1000;//执行间隔
        if(myTask==null){
            myTask = new MyTask(arg0.getServletContext());
            timer.schedule(new MyTask(arg0.getServletContext()), date, period);
   //timer.schedule(new CleanTpIpTask(arg0.getServletContext()), date);//只执行1次 //timer.schedule(new CleanTpIpTask(arg0.getServletContext()), 0, period);//项目启动立刻执行,每隔period 毫秒执行1次
        }
    }
}

 3.在web.xml中配置

  <listener>
      <listener-class>webservice.MyTaskListener</listener-class>
  </listener>

 

Javaweb中的定时器

标签:timertask   cal   cancel   code   pip   end   listen   mon   XML   

原文地址:https://www.cnblogs.com/dch0/p/12706608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!