How to implement task scheduling in Web engineering

Source: Internet
Author: User

Reprinted from: Http://www.oschina.net/question/146385_37793?sort=time

The following is a servlet listener combined with a Java timer to tell the entire implementation process. A servlet listener is required to implement the Javax.servlet.ServletContextListener interface while implementing its contextinitialized (Servletcontextevent event) and contextdestroyed (Servletcontextevent event) two interface functions. Considering the process of establishing and destroying the timer, looking at the previous two interface functions, it is undoubted to put the process of establishment into contextinitialized, and put the destruction process into contextdestroyed.

I named the Servletcontextlistener implementation class Contextlistener, adding a timer inside it, and the sample code is as follows (for space, only part of the code is available for readers to refer to):

?
1234567891011 private java.util.Timer timer = null;    public void contextInitialized(ServletContextEvent event){              timer = new java.util.Timer(true);              event.getServletContext().log("定时器已启动");                              timer.schedule(new MyTask(event.getServletContext()),0,60*60*1000);              event.getServletContext().log("已经添加任务调度表");    }    public void contextDestroyed(ServletContextEvent event){              timer.cancel();              event.getServletContext().log("定时器销毁");    }

In the above code, Timer.schedule (New MyTask (Event.getservletcontext ()), 0, 60*60*1000) This behavior timer dispatch statement, Where MyTask is a custom task that needs to be dispatched (in my Financial Data center project, which is the report calculation engine entry), inherited from Java.util.TimerTask, which is highlighted below, the third parameter indicates that an hourly (that is, 60*60*1000 milliseconds) is triggered once, The intermediate parameter 0 indicates no delay. The other code is fairly simple and is no longer detailed.

The following describes the implementation of MyTask, as seen in the code above, when constructing mytask, the Javax.servlet.ServletContext type parameter is passed in for the convenience of logging the servlet log. Therefore, you need to overload the MyTask constructor (whose parent class Java.util.TimerTask the original constructor is not a parameter). In Timer.schedule () scheduling, the hourly schedule is set, so if you want to implement a scheduled task every 24 hours, you also need to determine the clock point, the constant C_schedule_hour (12 o'clock, or 0 points). At the same time, to prevent 24 hours of execution, the task is not finished (of course, the general task is not so long), to avoid the second time is scheduled to cause the execution of the conflict, set the current is executing the status flag isrunning. The sample code looks like this:

?
1234567891011121314151617181920212223242526 private static final int C_SCHEDULE_HOUR = 0;     private static boolean isRunning = false;     private ServletContext context = null;     public MyTask(ServletContext context)   {             this.context = context;      public void run(){        Calendar cal = Calendar.getInstance();                        if(!isRunning){                                  if(C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)){                                         isRunning   =   true;                                                 context.log("开始执行指定任务");                                             //TODO   添加自定义的详细任务,以下只是示例                int i = 0;                while(i++ < 10){                     context.log("已完成任务的"+   i   +   "/"+   10);                }                isRunning   =   false;                context.log("指定任务执行结束");                                          }                                } else {            context.log("上一次任务执行还未结束");        }    }

The above code "//todo ..." below four lines is the demo code that is really scheduled to execute (in my Financial Datacenter Project is the report calculation process), you can replace the statement you want to execute.

Here, the code for Servletcontextlistener and MyTask is complete. The final step is to deploy Servletcontextlistener to your Web project and add the following three lines to your project's XML config file:

?
123 <listener    <listener-class>com.test.ContextListener</listener-class</listener>

Of course, the above com.test must be replaced by your own package name. Once you have saved the Web. xml file, deploy the project package to Tomcat. The task is executed from 12 o'clock in the evening to 1 o'clock in the morning, and the above code is recorded in the Tomcat log file as follows:

  2003-12-05   0:21:39   Start execution of specified tasks   
  2003-12-05   0:21:39   completed task 1/10 &NB SP;&NBSP
          &NBSP;&NBSP
  2003-12-05   0:21:39   completed task 10/10 &NB SP;&NBSP
  2003-12-05   0:21:39   Specify end of task execution  

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.