Java-Web定时任务

在Tomcat上进行Java Web项目的定时任务。

例如,定时更新趴取数据等。

步骤如下:

定义Task,继承TimerTask

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CrawlTask extends TimerTask {   

private static boolean isRunning = false;

public CrawlTask() {
}

public void run() {
if (!isRunning){
isRunning = true;
VehicleFactory.factory().startVehicleCrawl();
isRunning = false;
}
}
}

定义Timer类,实现ServletContextListener接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class TimerManager implements ServletContextListener {

private Timer timer = null;

@Override
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
}

@Override
public void contextInitialized(ServletContextEvent arg0) {
timer = new Timer("CrawlTimer",true);
timer.schedule(new CrawlTask(), 0, DateUtils.MILLIS_PER_DAY);
}

}

在web.xml中增加listener节点

1
2
3
<listener>
<listener-class>com.baidu.carlife.vehicle.TimerManager</listener-class>
</listener>