日期:2014-05-20 浏览次数:21031 次
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <listener> <listener-class>test.timer.TimerListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
package test.timer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class TimerListener implements ServletContextListener { @SuppressWarnings("unused") private ServletContext servletContext = null; private Timer timer = null; /** * 开始执行 */ @Override public void contextInitialized(ServletContextEvent e) { e.getServletContext().log("init !"); timer = new Timer(true); // 获得当天的日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "); Date date = new Date(); // 定义开始时间字符串 String timeStr = "12:00:00"; timeStr = sdf.format(date) + timeStr; // 获得当天的指定时间的date对象 sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { date = sdf.parse(timeStr); } catch (ParseException e1) { e1.printStackTrace(); } // 判断今天的执行时间是否已经过去,如果过去则改为明天 if (date.getTime() < System.currentTimeMillis()) { date = new Date(date.getTime() + 24 * 60 * 60 * 1000); } timer.schedule(new TestTimer(), date, 24*60*60 * 1000); } /** * 销毁 */ @Override public void contextDestroyed(ServletContextEvent e) { timer.cancel(); e.getServletContext().log("destroyed"); } }