A simple method of implementing timing task with Java in Web application

Source: Internet
Author: User
Tags final log log

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.