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>
  • 相关阅读:
    一个人的旅行 dij(),评测的时候有点惨
    CodeFroce Round 340 div2 E XOR and Favorite Number【莫队算法】
    [HihoCoder-1185] 连通性·三 【tarjan+缩点】
    2017百度之星初赛(A)1001,1005,1006解题报告
    HDU 5961&AOJ 821 传递
    pair
    优先队列 priority_queue
    ccf 201903-5
    memset 和 fill 的区别
    ccf 20190302
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/7126378.html
Copyright © 2011-2022 走看看