Web工程实现执行定时脚本主要是利用Servlet在启动的时候被载入,使用java.util.Timer来实现;
1.建立一个Web工程(AutoScript); 2.建立一个com.wangwz.autoscript.AutoTimerTask类;内容如下: package com.wangwz.autoscript; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimerTask; public class AutoTimerTask extends TimerTask { public void run() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(sdf.format(new Date()) + " I am running"); } } 3.建立com.wangwz.autoscript.AutoScript.java package com.wangwz.autoscript; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Timer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AutoScript extends HttpServlet { private static final long serialVersionUID = 1L; private Timer printTimer = null; private AutoTimerTask autoTimerTask = null; public AutoScript() { super(); } public void destroy() { System.out.println("YYYYYYYYYYYYYYY"); super.destroy(); if (this.printTimer != null) // 在Servlet停止的时候,关闭掉线程 this.printTimer.cancel(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void init() throws ServletException { System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); try { ServletContext sc = this.getServletContext(); String s = sc.getInitParameter("printtime"); printTimer = new Timer(); autoTimerTask = new AutoTimerTask(); Date doTime = new Date(); Date nowTime = new Date(); long timestamp = Long.parseLong(s); doTime.setHours(13); doTime.setMinutes(30); if (nowTime.after(doTime)) // 当前已经超过指定时间,刚设置到明天的13:30分执行 { doTime.setDate(doTime.getDate() + 1); } // 启动printTimer线程;执行的内容为printTimerTask;date为第一次执行时间;每隔timestamp再次执行一次 printTimer.schedule(autoTimerTask, doTime, timestamp); } catch (Exception e) { e.printStackTrace(); } } } 4.在web.xml中插入如下内容: <servlet> <servlet-name>AutoScript</servlet-name> <servlet-class>com.wangwz.autoscript.AutoScript</servlet-class> <load-on-startup>4</load-on-startup> </servlet> <servlet-mapping> <servlet-name>AutoScript</servlet-name> <url-pattern>/AutoScript</url-pattern> </servlet-mapping> <context-param> <param-name>printtime</param-name> <param-value>60000</param-value> <!--毫秒为单位,此为1分钟--> </context-param> 注:如果不是web工程,而是普通的JAVA工程,那么可以在JAVA类里面直接写Timer.schedule(TimerTask, doTime, timestamp); 我尝试过"实现ServletContextListener接口,在web.xml中配置这个监听器",不过出了如下问题: Tomcat+window下面正常;Resin+Linux下面不正常(当Resin中装多个工程时,每个工程都会经过这个监听器,因此会生成多个Timer) 不知道是否是我处理得有问题,如你有什么高见,请留言相教! |
JAVA执行定时脚本
最新推荐文章于 2024-07-12 17:09:31 发布