zoukankan      html  css  js  c++  java
  • Javaweb中的定时器

    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>
  • 相关阅读:
    戴尔英语09年互联网络投放策略规划书
    haproxy相关
    邮送广告
    python和rails交互应用
    ubuntu搭建邮件服务器
    waitr自动化测试
    ruby写爬虫
    free git svn repositories
    网站开发外包遇到的问题
    电影推荐
  • 原文地址:https://www.cnblogs.com/dch0/p/12706608.html
Copyright © 2011-2022 走看看