How to implement task scheduling in Web engineering

Source: Internet
Author: User
Tags constructor final tomcat

Many friends have used Windows task plan, there are many program fans have written the clock alarm, system automatic shutdown and other interesting programs, but few friends in the Web project to achieve similar functions. Today, I have the time to the author of the previous implementation of Tomcat similar functions, moved out to share with you.

As early as a few years ago, my company with a city Finance bureau cooperation project Development, in order to strengthen the Financial Bureau to the Unit's effective supervision of the State, the development, implementation of the Finance Bureau data Center project. This project uses b/S plus c/s mixed structure mode. The Financial Bureau on the Web server to set up data synchronous receiving device, by the municipal units every day before work to the finance information through the HTTP protocol uploaded to the Finance Bureau Central server, with the Web server reception device docking. Finance Bureau internal departments need to access a large number of financial information, access to complete municipal units of the current financial situation information, departments by functional division, the need for accurate access to the various departments concerned about the summary information, in the form of financial statements provided.

Due to the large amount of financial data, the real-time calculation of financial statements is slow, initially consider using the report cache to reduce the burden on the server, but with caching requires a reasonable cache update mechanism. Taking into account the municipal units before the end of the day before the financial data upload, the financial bureau to look up every day to see the accounting information does not include the day (unless there is a leader to wait until the owner of all uploaded to see the information, should have been off), so if you can achieve the task scheduling In the late night of the day and historical financial information Summary, update the cache, speed bottleneck is not resolved.

Because the system core was based on web deployments, the report calculation engine was deployed on the Tomcat container, so if you wanted to borrow Windows ' task plan to implement timed computations, it would be slightly more complicated to write an additional common desktop application interface. So I think about the implementation of the Web, after consulting more relevant information, found that the Java timer (java.util.Timer) has the function of timing trigger scheduled task, by configuring the timer interval, after a certain interval of time, automatic regular call scheduled task (Java.util.TimerTask). In addition, because we want the timer to start automatically when the Web project is started, the timer can trigger a report calculation engine every night late at night throughout the lifetime of the Web project. Therefore, the location of the timer is also worth checking, can not simply exist in a single servlet or JavaBean, must be able to keep the timer host lifetime for the entire Web project life, in the project startup can automatically load run. With these two points, the listener that is relevant to the servlet context is the most appropriate, and is properly configured in the project's configuration file, which runs automatically when the project is started and is monitored throughout the life of the project.

The following is a servlet listener that combines a Java timer to describe the entire implementation process. To use a servlet listener, you need to implement the Javax.servlet.ServletContextListener interface while implementing its contextinitialized (Servletcontextevent event) and contextdestroyed (Servletcontextevent event) two interface functions. Consider the timer has a process of establishment and destruction, looked at the first two interface functions, the establishment of the process is no doubt placed into the contextinitialized, the destruction of the process into the contextdestroyed.

I named the Servletcontextlistener implementation class as Contextlistener and added a timer inside it, as shown in the example code (for consideration of length, only part of the code is provided for reader's Reference):

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 execution task that needs to be scheduled (in my Financial data Center project is the report calculation engine portal), inherited from Java.util.TimerTask, and the third parameter means that every hour (that is, 60*60*1000 milliseconds) is triggered once, An intermediate parameter of 0 indicates no delay. Other code is fairly simple and no longer detailed.

The following is a description of the implementation of the MyTask, which is seen in the code above that the Javax.servlet.ServletContext type parameter was passed in for the convenience of logging the servlet log when the MyTask was constructed. It is therefore necessary to overload the MyTask constructor, whose parent class Java.util.TimerTask the original constructor without arguments. In Timer.schedule () scheduling, set the hourly schedule, so if you want to implement the scheduling task every 24 hours to be executed once, you also need to judge the clock point, the constant C_schedule_hour (12 o'clock, or 0 points). At the same time to prevent the 24-hour execution, the task has not yet been completed (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 state flag is currently executing isrunning. The sample code looks like this:

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 four lines below the "//todo ..." in the code above are the demo code that is really scheduled to execute (in my Financial data Center project is the report calculation process) and you can change to 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, adding the following three lines to your project's web.xml configuration file:

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

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

2003-12-05 0:21:39 Perform specified tasks

2003-12-05 0:21:39 1/10 of completed tasks

......

2003-12-05 0:21:39 10/10 of completed tasks

2003-12-05 0:21:39 specify end of task execution

The code above is debugged on Tomcat 4.1.29 and Tomcat 5.0.16. If you need complete code, please contact me through nbDeveloper@hotmail.com.

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.