zoukankan      html  css  js  c++  java
  • 用Java自定义一个定时器

    1.先定义一个监听类:

    import java.util.Date;
    import java.util.Timer;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    public class DemoListener implements ServletContextListener {
    
        private Timer timer = new Timer();
        
        public void contextDestroyed(ServletContextEvent event) {
            timer.cancel();
        }
    
        public void contextInitialized(ServletContextEvent event) {
            Date firstTime = new Date(System.currentTimeMillis());
            int period = 5;
            // 设置定时的开始时间和周期
            timer.schedule(new DemoTask(), firstTime, period * 1000);
        }
    
    }

    2.制定定时任务类:

    import java.net.UnknownHostException;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.TimerTask;
    
    import org.dom4j.DocumentException;
    
    public class DemoTask extends TimerTask {
        public void doSomething() throws UnknownHostException, DocumentException, ParseException {
            // 调用动作
            
            
            System.out.println("定时调用动作成功--------------------------------------------------------------------");
        }
    
        public void run() {
            try {
                doSomething();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    3.web.xml配置监听类

    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <web-app>
        <display-name>DemoTimer</display-name>
        <listener>
            <listener-class>DemoListener</listener-class>
        </listener>
    </web-app>
  • 相关阅读:
    最小瓶颈路
    HASH处理KMP算法
    忠诚
    程序自动分析
    图书管理
    银牛派对
    平均数
    抓住那头牛
    P2135 方块消除
    CSPS前最后一次模拟赛----爆炸的全过程
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/7126378.html
Copyright © 2011-2022 走看看