TimerDemo.java
package com.chase; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class TimerDemo implements ServletContextListener{ Timer timer; public TimerDemo() { timer = new Timer(); timer.schedule(new RemindTask(), 10000, 5000);//10000是启动时间,5000是间隔时间 } public void contextDestroyed(ServletContextEvent arg0) { System.out.println("contextDestroyed()------------------------------"); timer.cancel(); } public void contextInitialized(ServletContextEvent arg0) { System.out.println("contextInitialized()+++++++++++++++++++++++++++++++");//初始化就会运行 // new TimerDemo(); } class RemindTask extends TimerTask{ @Override public void run() { String greetings[] = {"--早上好","----上午好","------中午好","-------下午好","--------晚上好"}; System.out.println(System.currentTimeMillis()+greetings[new Random().nextInt(greetings.length)]); String surprise = ShuangSeQiu.surprise(1); } } public static void main(String[] args) { new TimerDemo(); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>com.chase.TimerDemo</listener-class> </listener> </web-app>