Quartz implementation of timing function example (servlet timer configuration method)

Source: Internet
Author: User


Quartz is an open-source job scheduling framework written entirely by Java, which provides a small example for everyone to refer to, and a way to configure the servlet

Quartz is an open source job scheduling framework written entirely by Java, which can be viewed on the http://www.opensymphony.com/quartz/official website.

Several core interfaces and classes of the quartz are:

Job Interface: Self-written "timer program" implement this interface of the void execute (Jobexecutioncontext arg0) method, the job also has a class of stateful statefuljob interface, if we need to finish the last job, This interface is required to implement the next job execution based on its execution results.
Trigger abstract class: The Dispatch Class (Scheduler) calls this class at time and then invokes the specified timer program by the trigger class.
Two types of triggers are provided in Quertz: Simpletrigger,crontrigger. The former is used to achieve relatively simple timing functions, such as the beginning of a few points, the end, how long to execute, the total number of secondary, the latter provides the use of expressions to describe the timing function, it is suitable for more complex timing description, such as the last month of the Friday, the weekly Thursday and so on.
Jobdetail class: Detailed description of a specific timing procedure, including Name,group,jobdatamap.
Jobexecutioncontext class: The run-time context of the timed program execution, which is used to get the name of the currently executing job, the configured parameters, and so on.
Jobdatamap class: A parameter that describes a job, which can be any base type, such as String,float, or a reference to an object.
Joblistener,triggerlistener interface: Used to listen for trigger status and job sweep status, perform the corresponding operation in close-up state.
Jobstore class: Where to execute the fixed program, optional in memory, in the database.

Simple Timing Program:

Copy the code code as follows:
public class Testjob implements Job
{
Public testjob () {}
public void execute (jobexecutioncontext arg0) throws Jobexecutionexception
{
String name = Context.getjobdetail (). Getjobdatamap (). getString ("name");
System.out.println ("Job executing ..." +name); }
}

public class Quartztest
{
public static void Main (string[] args)
{
Quartztest test = new Quartztest ();
Try
{
Test.startschedule ();
}
catch (Exception e)
{
E.printstacktrace ();
}
}
public void Startschedule () throws Exception
{
Scheduler Scheduler = Stdschedulerfactory.getdefaultscheduler ();
Jobdetail Jobdetail =
New Jobdetail ("Testjob", Scheduler.default_group, Testjob.class);
End time
Long end = System.currenttimemillis () + 9000L;
Executes 10 times, executes every 3 seconds, and ends in 9 seconds
Simpletrigger trigger = new Simpletrigger ("Test", Null,new date (), new date (end), 10,3000l);
Scheduler.schedulejob (Jobdetail, Trigger);
Scheduler.start ();
}
}

The implementation of the above class basically implements a simple timing program. But the problem is that now this class can only be applied in application, and in a Web environment it is necessary to add some configuration, such as adding servlets, adding configuration Files Quartz.properties or Quartz-job.xml ( Define Triiger, timed description, etc. in the XML file in the configuration mode.

Use in Web Apps

adding Quartzinitializerservlet,quartz in Web. XML to be able to be used in a website application provides a quartzinitializerservlet and a quartzinitializerlistener for loading the web When applied, initializes the quartz. I loaded successfully when I was using the servlet, I didn't succeed when I used listener, I didn't know what was going on.

Servlet configuration:
Copy the code code as follows:
<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>config-file</param-name>
<param-value>quartz.properties</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
Listener configuration can see the source code, the main parameters are configured as <context-param&gt, plus a <listener>.

The above mentioned quartz.properties, which is self-specified, Quartz provides a default configuration file to meet the basic J2SE application, if in the Web application, we want to write the Job,trigger configuration to the file, we need to write, and specify to load our own quratz.properties at initialization, where the position is placed under classes.

#============================================================================
# Configure Main Scheduler Properties
#============================================================================
Org.quartz.scheduler.instanceName = Org.quartz.scheduler.instanceId = AUTO
#============================================================================
# Configure ThreadPool
#============================================================================
Org.quartz.threadPool.class = Org.quartz.simpl.SimpleThreadPool
Org.quartz.threadPool.threadCount = 3
Org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure Plugins
#============================================================================
Org.quartz.plugin.triggHistory.class = Org.quartz.plugins.history.LoggingJobHistoryPlugin
Org.quartz.plugin.jobInitializer.class = Org.quartz.plugins.xml.JobInitializationPlugin
Org.quartz.plugin.jobInitializer.fileName =/scheduler/quartz_jobs.xml
Org.quartz.plugin.jobInitializer.overWriteExistingJobs = True
Org.quartz.plugin.jobInitializer.failOnFileNotFound = True
Org.quartz.plugin.jobInitializer.scanInterval = 10

Quartz to use a plugin to load its own XML configuration file, we specified that loading the classes/scheduler/quartz_jobs.xml at initialization time, the default is to load the Classes/quartz_jobs.xml file.

Quartz_jobs.xml file:
<?xml version= ' 1.0 ' encoding= ' utf-8 '?>
<quartz>
<job>
<job-detail>
<name>test</name>
<group>DEFAULT</group>
<description>testJobhere</description>
<job-class>TestJob</job-class>
<job-data-map allows-transient-data= "true" >
<entry>
<key>name</key>
<value>test</value>
</entry>
</job-data-map>
</job-detail>
<trigger>
<cron>
<name>testCron</name>
<group>DEFAULT</group>
<job-name>test</job-name>
<job-group>DEFALUT</job-group>
&LT;CRON-EXPRESSION&GT;0/3 * * * *?</cron-expression>
</cron>
</trigger>
</job>
</quartz>


It is configured with a job and declares a parameter name; a Crontrigger is configured to execute once every three seconds. If you want to configure Simpletrigger, you can use the <simple> tab.

The class corresponding to the job above is testjob, and the source code is:

Copy the code code as follows:
public class Testjob implements Job
{
Public testjob () {}
public void execute (jobexecutioncontext context) throws Jobexecutionexception
{
String name = Context.getjobdetail (). Getjobdatamap (). getString ("name");
System.out.println ("Job executing ..." +name);
}
}


You can also specify Triggerlistener,joblistener in the Quartz_job.xml file, which can be specified using the <trigger-listener>,<job-listener> tag.

Because quartz current documents are not many, most of them are looking at the source code. Overall, Quartz provides crontrigger using expressions to describe timing rules This function is still very powerful, there are many examples in its source code.

Spring has integrated the quartz and has been packaged to make it easy to use.

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.