在java 项目启动时,web.xml启动时,自行运行Listener监听对应的类,运行定时器。
1.web.xml中配置信息
<listener>
<listener-class>
com.test.demo.ListenerDemo
</listener-class>
</listener>
2.事件监听的类
package com.test.listener;
import java.util.Date;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ListenerDemo implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
Timer timer = new Timer();//new一个定时器对象
TaskDemo task = new TaskDemo();
timer.schedule(task, new Date(), 1000);//当前时间开始,每个一秒钟执行一次定时任