A simple method to implement timed tasks under Web application
In Web mode, if we want to implement certain tasks on a regular basis, in addition to using quartz and other third-party open source tools, we can use timer and Timetask to complete the specified timing tasks:
The first step: Create a task management class, implement Servletcontextlistener interface
The following is a reference fragment:
public class TaskManager implements ServletContextListener {
/**
* 每天的毫秒数
*/
public static final long PERIOD_DAY = DateUtils.MILLIS_IN_DAY;
/**
* 一周内的毫秒数
*/
public static final long PERIOD_WEEK = PERIOD_DAY * 7;
/**
* 无延迟
*/
public static final long NO_DELAY = 0;
/**
* 定时器
*/
private Timer timer;
/**
* 在Web应用启动时初始化任务
*/
public void contextInitialized(ServletContextEvent event) {
//定义定时器
timer = new Timer("数据库表备份",true);
//启动备份任务,每月(4个星期)执行一次
timer.schedule(new BackUpTableTask(),NO_DELAY, PERIOD_WEEK * 4);
// timer.schedule(new BackUpTableTask(),NO_DELAY, 30000);
}
/**
* 在Web应用结束时停止任务
*/
public void contextDestroyed(ServletContextEvent event) {
timer.cancel(); // 定时器销毁
}
}
Step Two: Create a Time task class
The following is a reference fragment:
public class BackUpTableTask extends TimerTask {
private static Log log = LogFactory.getLog(BackUpTableTask.class);
private static boolean isRunning = false;
public void run() {
if (!isRunning) {
isRunning = true;
log.debug("开始执行任务..."); //开始任务
//working add what you want to do
log.debug("执行任务完成..."); //任务完成
isRunning = false;
} else {
log.debug("上一次任务执行还未结束..."); //上一次任务执行还未结束
}
}
}
Step three: Add a listener to the web
The following is a reference fragment:
<listener>
<listener-class>***.TaskManager</listener-class>
<description>要定期执行的任务</description>
</listener>
When the Web server is started, the task is also started and periodically executed.