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); } }