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>
  • 相关阅读:
    pat 1044 Shopping in Mars
    PAT1017 Queueing at Bank
    PAT1023 Have Fun with Numbers
    PAT1020
    谈谈软件测试职业规划
    测试工程师的一些思考
    浅谈性能测试
    软件测试价值提升之路- 第三章"拦截缺陷 "读书笔记
    软件测试价值提升之路- 第二章"价值实现的起点"读书笔记
    UI 自动化框架设想
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/7126378.html
Copyright © 2011-2022 走看看