How to implement effective task scheduling in Java Web applications

Source: Internet
Author: User
Tags thread java web

Why do I need task scheduling?

In Web applications, most tasks are done in a way that prevents users from waiting for a long time. In examples such as Google search, reducing latency is critical to the user experience. One solution to an asynchronous task is to generate a thread (to handle asynchronous tasks) after the user submits it, but it does not solve situations where tasks need to be run repeatedly at a certain interval or at a specified time of day.

Let's take a look at the example of a database report to see how task scheduling can help improve system design. Reports can be complex, depending on the type of data you need and whether you need to collect large amounts of data from one or more databases. It may take a long time for the user to run such an on-demand report. Therefore, we add a task scheduling mechanism to the quote example so that users can schedule reports to be generated at any time they need and sent in email in PDF or other format. Users can make the report run at a low load of 2:22 every day, or you can choose to run it only once at a specific time. By adding task scheduling to the report application, we can add a useful feature to the product and improve the user experience.

Fortunately, there is a powerful open source solution that allows us to implement task scheduling in a standard way in a Web application (or any Java application). The following example shows how to use quartz to create a task scheduling framework in a Web application. The example also uses the Struts Action framework plug-in to initialize the task scheduling mechanism when the Web application starts. Struts is the most common MVC framework that is familiar to most developers. There are, of course, many other frameworks that can help implement the MVC pattern in Web applications.

Initializing Task Scheduler at startup

The first thing we have to do is build a struts plug-in to create our task Scheduler when the container starts. In the following example, we chose Tomcat as the Web application container, but these examples should also work in other containers. We're going to create a struts plug-in class and add a few lines of code to the Struts-config.xml to make it work.

This plug-in has two configurable initialization parameters: startonload Specifies whether to start the Task Scheduler as soon as the container is started, and startupdelay specifies the wait time before the Task Scheduler is started. Startup latency is useful because we may need to perform some more important initialization steps first. In addition, you can use the listener mechanism to inform schedulerplugin when to start quartz Scheduler in a more complex way.

<PLUG-IN className="SchedulerPlugIn">
<SET-PROPERTY property="startOnLoad" value="false" />
<SET-PROPERTY property="startupDelay" value="0" />
</PLUG-IN>

What we want to create is a list class Schedulerplugin that implements the Struts plug-in interface org.apache.struts.action.PlugIn. Struts initializes each plug-in in the order in which it appears in the configuration file. Special attention is given to the code in the Init () method, where we initialize the desired Quartz object and get scheduler. Our task information is to be submitted to this Org.quartz.Scheduler object, which will be discussed later. The Scheduler object is initialized by the quartz servlet based on its configuration, just as struts initializes its Actionservlet class. Let's look at the init () method:

public void init (Actionservlet actionservlet,
Moduleconfig moduleconfig) {
System.out.println (" Initializing Scheduler PlugIn for jobs! ");
//Retrieve the ServletContext
//Get ServletContext
ServletContext ctx = Actionservlet.getservletcontext (); br>//The Quartz Scheduler
//Quartz Scheduler object
Scheduler Scheduler = null;
//Retrieve the factory from the ServletContext.
//It'll be putting there by the Quartz servlet
///from ServletContext to get the factory object placed here by the Quartz servlet.
Stdschedulerfactory factory = (stdschedulerfactory)
Ctx.getattribute (quartzinitializerservlet.quartz_ Factory_key);
try{
//Retrieve the scheduler from factory
//Get factory from Scheduler
Scheduler = Factory.getscheduler () ;
//Start the scheduler in case, it isn ' t started yet
//If scheduler has not been started, start it
if (m_startonload!= null && Amp
M_startonload.equals (Boolean.TRUE.toString ())) {
System.out.println ("Scheduler'll start in" +
M_Startupdelaystring + "milliseconds!");
//wait The specified amount of time before
//starting the process.
//To wait for a specified length before starting
Thread delayedsched Uler =
New Thread (New delayedschedulerstarted (
Scheduler, M_startupdelay));
//give the Scheduler a name. All good the code needs a name
//is named to the Task Scheduler. Good code should always have a name!
Delayedscheduler.setname ("Delayed_scheduler");
//start Out Scheduler
//Start Task Scheduler
Delayedscheduler.start ();
}
} catch (Exception e) {
E.printstacktrace ();
}
Sm_scheduler = Scheduler;
}

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.