• java中服务器启动时,执行定时任务


    package com.ripsoft.util;
    
    import java.util.Calendar;
    import java.util.Timer;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    public class TimerListener implements ServletContextListener{
        private Timer timer = null;  
          
        @Override  
        public void contextInitialized(ServletContextEvent event) {  
            timer = new Timer(true);  
            event.getServletContext().log("定时器已启动");  
           
          //设置执行时间
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
            //定制每天的11:00:00执行
            calendar.set(year, month, day, 11, 00, 00);
            java.util.Date date = calendar.getTime();
            int period = 30 * 1000;
            //每天的date时刻执行TestTask,每隔30秒重复执行
            timer.schedule(new TestTask(), date, period);
            //每天的date时刻执行TestTask, 仅执行一次
            //timer.schedule(new TestTask(), date);
        }  
      
        @Override  
        public void contextDestroyed(ServletContextEvent event) {  
            if (timer != null) {  
                timer.cancel();  
                event.getServletContext().log("定时器销毁");  
            }  
        }  
    }
    package com.ripsoft.util;
    
    import java.util.TimerTask;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    public class TestTask extends TimerTask{
        protected final Log logger = LogFactory.getLog(getClass());  
          
        private static boolean isRunning = false;  
      
        @Override  
        public void run() {  
            if (!isRunning) {  
                isRunning = true;  
                logger.info("开始执行任务。");  
      
                int i = 0;  
                while (i++ < 10) {  
                    logger.info("已完成任务的" + i + "/" + 10);  
                }  
      
                isRunning = false;  
                logger.info("任务执行结束。");  
      
            } else {  
                logger.info("上一次任务执行还未结束,本次任务不能执行。");  
            }  
      
        }  
    }

    1.TestTimerListener.java执行定时任务,实现servlet的ServletContextListener接口,当服务器启动时开始执行TestTask任务

    2.想要任务在服务器启动时定时执行,就要借助监听实现需要在web.xml中做如下配置

        <listener>
            <listener-class>com.ripsoft.util.TimerListener</listener-class>
        </listener>
  • 相关阅读:
    spring 常用注解
    自定义Repository
    Python生成连续数字的多种方式
    HTML&CSS学习笔记
    ZigBee学习笔记
    Win10系统采用虚拟机安装Ubuntu18.04进行NS3开发环境配置
    Git速查笔记
    历史向网址收藏
    图解设计模式转载
    Crush Course 统计学笔记
  • 原文地址:https://www.cnblogs.com/qiuting/p/6076907.html
Copyright © 2020-2023  润新知