• 用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>
  • 相关阅读:
    SQL数据转移
    怎么将控制台的打印输出到文本文件中
    用来控制 XML 序列化的属性
    excel内容转成xml
    HTTP状态码
    char、varchar、nchar、nvarchar的区别
    C# Cookie编程
    android的原理--为什么我们不需要手动关闭程序
    HTTP协议及HTTP包
    HTTP 方法:GET 对比 POST
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/7126378.html
Copyright © 2020-2023  润新知