Use quartz to implement the timing Function

Source: Internet
Author: User
Quartz is an open-source job scheduling framework fully compiled by Java. For details, visit http://www.opensymphony.com/quartz/. The core interfaces and classes of quartz are:   Job Interface: The Void execute (jobexecutioncontext arg0) method for self-written "Timer Program" to implement this interface. Job also has a stateful statefuljob interface. If we need to finish executing the previous job, this interface is required to execute the next job based on the execution result. Trigger abstract class: The scheduling class (schedgger) calls this class at the time, and then the trigger class calls the specified Timer Program. Quertz provides two types of triggers: simpletrigger and crontrigger. The former is used to implement relatively simple timing functions, such as the start time, end time, interval execution time, and total number of executions. The latter provides the function to describe timing using expressions, therefore, it is suitable for complex timing descriptions, such as the last Friday of each month and the last Thursday of each week. Jobdetail class: A detailed description of a specific Timer Program, including name, group, and jobdatamap. Jobexecutioncontext class: The context of the run-time execution of the timer program. It is used to obtain the name of the currently executed job and the configured parameters. Jobdatamap class: A parameter used to describe a job. A parameter can be of any basic type, such as string or float, or can be referenced by an object. Joblistener, triggerlistener Interface: Used to listen to the trigger status and job row scanning status, and perform corresponding operations in the close-up status. Jobstore class: Where to execute the preset program, which can be in the memory or in the database. Simple Timer Program: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 schedfactory = stdschedulerfactory. getdefaschscheduler ();
Jobdetail =
New jobdetail ("testjob", scheduler. default_group, testjob. Class );
// End time long end = system. currenttimemillis () + 9000l; // execute 10 times, once every 3 seconds, ends after 9 seconds
Simpletrigger trigger = new simpletrigger ("test", null, new date (), new date (end), 10,300 0l );
Scheduler. schedulejob (jobdetail, trigger );
Scheduler. Start ();
}
} Execute the above class to basically implement a simple Timer Program. However, the problem is that this class can only be applied in the application, and some configuration needs to be added in the web environment, such as adding Servlet and adding the configuration file quartz. properties or quartz-job.xml (define triiger, timed description, etc. in the XML file as a configuration ). Use in Web Applications  

Add quartzinitializerservlet to Web. xml. Quartz provides a quartzinitializerservlet and a quartzinitializerlistener to initialize quartz when loading a web application. When I use servlet, the load is successful. When I use listener, the load is unsuccessful. Why not?

 

Servlet configuration: <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> the listener configuration can be viewed in the source code. The main parameter configuration above is <context-param>, and a <listener>. the above mentioned quartz. properties, which is self-specified. Quartz provides a default configuration file, which can meet the requirements of basic j2se applications, when all trigger configurations are written to the file, you need to write them yourself and specify to load our own quratz during initialization. properties in the classes directory. #===================================================== ============================================
# 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. loggingjobhistorypluginorg. quartz. plugin. jobinitializer. class = org. quartz. plugins. XML. jobinitializationplugin
Org. Quartz. plugin. jobinitializer. filename =/schedename/quartz_jobs.xml
Org. Quartz. plugin. jobinitializer. overwriteexistingjobs = true
Org. Quartz. plugin. jobinitializer. failonfilenotfound = true
Org. quartz. plugin. jobinitializer. scaninterval = 10 Quartz needs to use ins to load their xml configuration files. above we specify to load classes/schedses/quartz_jobs.xml during initialization. The default value 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>
<Cron-expression> 0/3 ****? </Cron-expression>
</Cron>
</Trigger>
</Job>
</Quartz>

A job is configured and a parameter name is declared. A crontrigger is configured and executed every three seconds. To configure simpletrigger, you can use the <simple> label. The class corresponding to the job above is testjob, and the source code is: 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 );
}
} In the quartz_job.xml file, you can also specify triggerlistener and joblistener. You can use the <trigger-listener> and <job-listener> labels to specify them. Since there are not many quartz documents currently, most of them are source code. In general, the crontrigger provided by quartz uses expressions to describe the timing rule. There are many examples in its source code. Spring has integrated and encapsulated quartz, which is 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.