用Java自定义一个定时器
1.先定义一个监听类:
import java.util.Date; import java.util.Timer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class DemoListener implements ServletContextListener { private Timer timer = new Timer(); public void contextDestroyed(ServletContextEvent event) { timer.cancel(); } public void contextInitialized(ServletContextEvent event) { Date firstTime = new Date(System.currentTimeMillis()); int period = 5; // 设置定时的开始时间和周期 timer.schedule(new DemoTask(), firstTime, period * 1000); } }
2.制定定时任务类:
import java.net.UnknownHostException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.TimerTask; import org.dom4j.DocumentException; public class DemoTask extends TimerTask { public void doSomething() throws UnknownHostException, DocumentException, ParseException { // 调用动作 System.out.println("定时调用动作成功--------------------------------------------------------------------"); } public void run() { try { doSomething(); } catch (Exception e) { e.printStackTrace(); } } }
3.web.xml配置监听类
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <display-name>DemoTimer</display-name> <listener> <listener-class>DemoListener</listener-class> </listener> </web-app>