zoukankan      html  css  js  c++  java
  • 定时器tasktimer

    1、web.xml中配置

    <servlet> 
    <servlet-name>TaskTimer</servlet-name> 
    <servlet-class>com.XXXXX.controller.TaskTimer</servlet-class> 
    <load-on-startup>2</load-on-startup> 
    </servlet>

    2、写实现方法

    package com.XXX.controller;
    
    import java.util.Date;
    import java.util.Timer;  
    import java.util.TimerTask;
    
    import javax.servlet.http.HttpServlet;
    
    public class TaskTimer extends HttpServlet{
        
        private static final long serialVersionUID = 1L;
    
        public void init(){
            Timer timer = new Timer();    
            timer.schedule(new TimerTask() {    
                public void run() {    
                    System.out.println(new Date()+"-----Hello !!!");
                }    
            }, 1000*5, 1000*3);//第二个参数为多少毫秒后启动,第三个参数为每个多少毫秒执行一次
        }
    }

     若在TaskTimer中调用service,用@Autowired注入,启动项目会报空指针错误,原因及分析可查看此文档

    因此对代码进行修改

    package com.XXXX.controller;
    
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    import java.util.Timer;  
    import java.util.TimerTask;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.http.HttpServlet;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    @Controller
    public class TaskTimer extends HttpServlet{
        private static final long serialVersionUID = 1L;
    
        public void init(){
            final ServletContextEvent sce = new ServletContextEvent(getServletContext());
    Timer timer = new Timer(); timer.schedule(new TimerTask() { //获得Spring容器 WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); //从Spring容器中获得SelectDataServlet的实例 private Service service = ctx.getBean(service.class);public void run() { System.out.println("已经开始跑定时器");
              //定时器主体,此处可调用service实体
    } }, 1000*5, 1000*60*60*24); } }
  • 相关阅读:
    寄存器基础知识
    基础知识
    架构
    Mac下Apache服务器的初步搭建
    ios字体简单设定
    xcode中自定义log打印
    jQuery打印插件
    ionic3生命周期钩子
    ES5 数组方法map
    $compile的妙用
  • 原文地址:https://www.cnblogs.com/xiufengd/p/8334966.html
Copyright © 2011-2022 走看看