首先创建监听器:
public class ScheduleListener implements ServletContextListener {
private static ScheduledExecutorService service4Check;
@Override
public void contextInitialized(ServletContextEvent event) {
createSchedule();
}
private static void createSchedule() {
CheckSchedule();
}
private static void CheckSchedule() {
service4Check=Executors.newScheduledThreadPool(1);
service4Check.scheduleWithFixedDelay(new CheckTask(), 1000, 180*1000,
TimeUnit.MILLISECONDS);//每3分钟执行一次
}
public class CheckTask extends TimerTask{
@Override
public void run() {
//要定时执行的任务
}
}
}
然后在web.xml文件中添加监听器:
<listener>
<listener-class>com.xxx.ScheduleListener</listener-class>
</listener>
启动Tomcat后,该定时器会自动执行。