How to schedule tasks in a Web project

Source: Internet
Author: User

Many friends have used Windows Task plans, and many program fans have written interesting programs such as clock alarms and automatic system shutdown, but few of them have implemented similar functions in the Web project. Today, I am free to share with you the similar functions previously implemented on Tomcat.
As early as a few years ago, our company cooperated with a city Finance Bureau to develop a project. In order to strengthen the Finance Bureau's effective supervision on the financial status of the Organization, we developed and implemented the Finance Bureau data center project. This project adopts the B/S + C/S hybrid structure mode. The Finance Bureau sets up a data synchronization receiving device on the Web server. The municipal organization uploads the financial information to the Finance Bureau's central server through HTTP before getting off work every day, and connects it with the receiving device on the Web server. Various departments in the Finance Bureau need to check a large amount of financial information to obtain complete information on the current financial status of the municipal units. Each department is divided by function and needs to accurately obtain the summary information of each department's respective concerns, provided in the form of financial statements.
Because of the large amount of financial data and the slow speed of real-time computing of financial reports, we initially considered using report cache to reduce the burden on the server. However, using a cache requires a reasonable cache update mechanism. Taking into account that each municipal unit uploads financial data before getting off work every day, the financial information that the Finance Bureau checks every day does not actually include the current day (unless a leader waits until all the affiliated units are uploaded to view the information, it should have been off work), so if you can implement task scheduling and summarize the day and historical financial information every night, update the cache, the speed bottleneck will not be solved.
At that time, because the core of the system was deployed on the Web, the report computing engine was also deployed on the Tomcat container. Therefore, if you want to use the Windows Task Plan for scheduled computing, you need to write additional interfaces for common desktop applications, which is a little complicated. So I thought about how to implement it on the Web. After reading a lot of relevant information, I found that Java timer (java. util. timer) has the function of regularly triggering scheduled tasks. By configuring the Timer interval, scheduled tasks (java. util. timerTask ). In addition, we hope that when the Web project is started, the timer can automatically start timing. during the lifetime of the Web project, the timer can trigger a report computing engine every night. Therefore, the storage location of the timer is also worth examining. It cannot simply exist in a single Servlet or JavaBean. It must enable the lifetime of the timer host to be the whole Web project and automatically load and run when the project starts. In combination with these two points, the listener related to the Servlet context is the most suitable. By properly configuring the configuration file in the project, the listener will automatically run at the project startup, it is monitored throughout the project lifecycle.
The following describes the entire implementation process by combining the Servlet listener with the Java timer. To use the Servlet listener, you must implement the javax. servlet. ServletContextListener interface and its contextInitialized (ServletContextEvent event) and contextDestroyed (ServletContextEvent event) interface functions. Considering that the timer has a creation and destruction process, after reading the first two interface functions, we can undoubtedly put the creation process into contextInitialized and the destruction process into contextDestroyed.
I named the implementation class of ServletContextListener as ContextListener, and added a timer to it. The sample code is as follows (for space consideration, only part of the code is provided for your reference ):

  1. PrivateJava. util.TimerTimer =Null;
  2. Public VoidContextInitialized (ServletContextEvent event ){
  3. Timer =NewJava. util.Timer(True);
  4. Event. getServletContext (). log ("timer started ");
  5. Timer. schedule (NewMyTask (event. getServletContext (), 0, 60*60*1000 );
  6. Event. getServletContext (). log ("added task scheduling table ");
  7. }
  8. Public VoidContextDestroyed (ServletContextEvent event ){
  9. Timer. cancel ();
  10. Event. getServletContext (). log ("timer destruction ");
  11. }


In the above Code, timer. schedule (new MyTask (event. getServletContext (), 0, 60*60*1000) is a timer scheduling statement, myTask is a custom execution task to be scheduled (in my financial data center project, it is the report computing engine portal. util. timerTask inheritance, which will be highlighted below. The third parameter table indicates that the task is triggered every hour (that is, 60*60*1000 milliseconds). The intermediate parameter 0 indicates no delay. Other code is quite simple and will not be described in detail.
The following describes the implementation of MyTask. The code above shows that javax is passed in when constructing MyTask. servlet. servletContext type parameters are input to record Servlet logs conveniently. Therefore, you need to reload the constructor of MyTask (its parent class is java. util. the original TimerTask constructor has no parameters ). In timer. schedule () is scheduled every hour. Therefore, if you want to schedule a task to be executed every 24 hours, you need to determine the clock point, it is represented by the constant C_SCHEDULE_HOUR (, that is ). At the same time, to prevent 24-hour execution, the task has not been completed (of course, the general task is not so long), so as to avoid the second scheduling to cause execution conflicts, sets the status flag isRunning that is currently being executed. The sample code is as follows:

  1. Private Static Final IntC_SCHEDULE_HOUR = 0;
  2. Private Static BooleanIsRunning =False;
  3. PrivateServletContext context =Null;
  4. PublicMyTask (ServletContext context ){
  5. This. Context = context;
  6. }
  7. Public VoidRun (){
  8. Calendar cal = Calendar. getInstance ();
  9. If(! IsRunning ){
  10. If(C_SCHEDULE_HOUR = cal. get (Calendar. HOUR_OF_DAY )){
  11. IsRunning =True;
  12. Context. log ("starting to execute a specified task ");
  13. // Add custom detailed tasks to TODO. The following is an example.
  14. IntI = 0;
  15. While(I ++ <10 ){
  16. & Nbs

Related Article

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.