"Quartz" in-depth job, Jobdetail, Jobdatamap, Trigger

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

The Quartz API core interfaces are:

    • scheduler– the main API to interact with Scheduler;
    • job– you perform tasks through scheduler, your task class needs to implement the interface;
    • jobdetail– defines an instance of the job;
    • trigger– triggers the execution of the job;
    • jobbuilder– defines and creates interfaces for Jobdetail instances;
    • triggerbuilder– defines and creates interfaces for trigger instances;

First, Job

In the previous section, the actual business logic was defined in the job, and Jobdetail contains the job-related configuration information. In quartz, each time scheduler executes a job, before calling its execute () method, it needs to create an instance of the job class based on the job type provided by Jobdetail, and after the task has finished executing, the job Instances of class are discarded, and the JVM's garbage collector recycles them. therefore, when writing a specific implementation of the job, it is important to note:

(1) It must have a non-parametric constructor;

(2) It should not have a static data type because it is recycled after each job execution, so static data cannot be maintained during multiple executions.

There is such a member in Jobdetail. Jobdatamap,jobdatamap is a concrete implementation of the Java map interface and adds a handy way to store and read the native type data, which contains all the data objects that you want to provide to it when the job instance runs.

You can use Jobdatamap to provide a property/configuration for the job instance, which can be used to track job execution status and so on. In the first case, you can add Jobdatamap data when creating the job, get the data in the job's execute (), and the second, you can track the execution status of the job in listener by getting the state data stored in the Jobdatamap.

A Java class that implements the job interface can be executed by the scheduler. The interface is as follows:

Packageorg.quartz;publicinterface Job {public void execute (jobexecutioncontext context) throwsjobexecutionexception;}

very simple, when the job's trigger is triggered, the job's execute (..) method is called by the scheduler. The Jobexecutioncontext object that is passed to this method provides information with the job Runtime: The scheduler handle that executes it, the trigger handle that triggers it, the job's Jobdetail object, and some other items. The Jobdetail object is created when the job is added to the scheduler, it contains a lot of job property settings, and, like Jobdatamap, some state information that can be used to store the job instance.

For example, the following task class

Package Com.mucfc;import Java.util.date;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import Org.quartz.job;import Org.quartz.jobdetail;import Org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;public class NewJob implements Job{static Log   Logger = Logfactory.getlog (Newjob.class);  @Overridepublic void Execute (Jobexecutioncontext context) throws Jobexecutionexception {System.err.println ("hello! Newjob is executing. "            +new Date ());//Get job details Jobdetail jobdetail = Context.getjobdetail ();         Get job name String JobName = Jobdetail.getclass (). GetName ();            Logger.info ("Name:" + jobdetail.getclass (). Getsimplename ());            Get Job class Logger.info ("Job class:" + Jobdetail.getjobclass ());           Get Job start time Logger.info (JobName + "fired at" + context.getfiretime ()); Logger.info ("Next Fire Time" + context.getnextfiretime ());}}


when Scheduler invokes a Job, a jobexecutioncontext is passed to the Execute () method. The Jobexecutioncontext object allows the job to access the details of the Quartz runtime environment and the job itself. This is similar to a servlet accessing ServletContext in a Java Web application. All information about your environment is accessible through jobexecutioncontext,job, including Jobdetail and Triiger that are registered with the Job on Scheduler.

Second, Jobdetail

Jobdetail instances are created through the Jobbuilder class

You can import all the static methods under this class

       Import static org.quartz.jobbuilder.*;
then it is created:
        Create a Jobdetail instance        jobdetail jobdetail = Newjob (Newjob.class). Withidentity ("Job1_1", "JGroup1"). Build ();
If you do not import a static package:

Then you need to use:

Create a Jobdetail instance obdetail jobdetail = Jobbuilder.newjob (Newjob.class). Withidentity ("Job1_1", "JGroup1"). Build ();

Only one Jobdetail instance is created for each Job that is deployed on Scheduler. The jobdetail is defined as a Job instance. Notice that the Job object is not registered to Scheduler in the code, and is actually registered as a Jobdetail instance.

public void Startschedule () {try {//1, create a Jobdetail instance, specify Quartzjobdetail Jobdetail = Jobbuilder.newjob (newjob.class)// Task execution class. Withidentity ("Job1_1", "jGroup1")//Task Name, Task Group. Build ();//2, create Triggersimpleschedulebuilder builder= Simpleschedulebuilder.simpleschedule (). Withintervalinseconds (5)//Set interval execution time. Repeatsecondlyfortotalcount (5);// Set the number of executions trigger Trigger=triggerbuilder.newtrigger (). Withidentity ("Trigger1_1", "TGroup1"). Startnow (). Withschedule ( Builder). Build ();//3, create Schedulerscheduler scheduler=stdschedulerfactory.getdefaultscheduler ();//4, Dispatch execution Scheduler.schedulejob (jobdetail, trigger); Scheduler.start ();} catch (Schedulerexception e) {e.printstacktrace ();}}
Results:


From the code above you can see that Jobdetail is added to Scheduler instead of the job. The job class is part of the jobdetail, but it is not instantiated until Scheduler is ready to execute it.

The Job instance is not created until it is executed

Instances of the Job will not be instantiated until they are executed. Each time the job is executed, a new job instance is created. The implication of this is that your Job does not have to worry about thread safety, because only one thread at a time executes instances of a given job class, even concurrently executing the same job.

As you can see, we pass to scheduler a Jobdetail instance, because when we create Jobdetail, the class name of the job to be executed is passed to Jobdetail, so scheduler knows what type of job to perform Each time scheduler executes a job, it calls its execute (...). A new instance of the class is created before the method is executed, the reference to the instance is discarded, and the instance is garbage collected; one consequence of this execution strategy is that the job must have a parameterless constructor (when using the default jobfactory), and the other consequence is that in the job class, Stateful data properties should not be defined because the values of these properties are not persisted in the job's multiple executions.

So how do you add properties or configuration to a job instance? How do you track the status of a job in multiple executions of the job? The answer is: part of the Jobdatamap,jobdetail object.

Third, Jobdatamap

The Jobdatamap can contain an unlimited (serialized) data object, which can be used when the job instance executes, and Jobdatamap is an implementation of the Java Map interface, adding additional methods to facilitate access to basic types of data.

Before you join the job to scheduler, you can put the data into jobdatamap when building jobdetail, as in the following example:

Package Com.mucfc;import Org.quartz.job;import Org.quartz.jobdatamap;import org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;import Org.quartz.jobkey;public class NewJob2 implements job{@Overridepublic void Execute (Jobexecutioncontext context) throws Jobexecutionexception {     Jobkey key = Context.getjobdetail (). GetKey ();         Jobdatamap DataMap = Context.getjobdetail (). Getjobdatamap ();         String jobsays = datamap.getstring ("Jobsays");         float Myfloatvalue = datamap.getfloat ("Myfloatvalue");         System.out.println ("Instance" + key + "of Dumbjob says:" + Jobsays + ", and Val is:" + Myfloatvalue);}}

During job execution, data can be extracted from jobdatamap, as in the following example:

Package Com.mucfc;import Org.quartz.jobbuilder;import Org.quartz.jobdetail;import org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.quartz.simpleschedulebuilder;import Org.quartz.Trigger;import Org.quartz.triggerbuilder;import Org.quartz.impl.stdschedulerfactory;public class Test {public void Startschedule () { try {//1, create a Jobdetail instance, specify Quartzjobdetail Jobdetail = Jobbuilder.newjob (newjob.class)//Task execution class. Withidentity ("Job1_1 "," jGroup1 ")//Task Name, Task Group. build (); Jobdetail jobDetail2 = Jobbuilder.newjob (Newjob2.class). Withidentity ("Job1_2", "JGroup1"). Usingjobdata ("Jobsa      Ys "," Hello world! ") . Usingjobdata ("Myfloatvalue", 3.141f). Build ();//2, create Triggersimpleschedulebuilder builder= Simpleschedulebuilder.simpleschedule (). Withintervalinseconds (5)//Set interval execution time. Repeatsecondlyfortotalcount (5);// Set the number of executions trigger Trigger=triggerbuilder.newtrigger (). Withidentity ("Trigger1_1", "TGroup1"). Startnow (). Withschedule ( Builder). Build ();//3, create Schedulerscheduler scheduler=stdscheduLerfactory.getdefaultscheduler ();//4, dispatch execution Scheduler.schedulejob (JOBDETAIL2, trigger); Scheduler.start ();} catch (Schedulerexception e) {e.printstacktrace ();}} public static void Main (string[] args) {test test=new test (); Test.startschedule ();}}

Results:



Iv. Trigger

the Trigger object is used to trigger the execution of the job. When scheduling a job, we instantiate a trigger and then adjust its properties to meet the conditions of the job execution. The trigger also has a jobdatamap associated with it, which is used to send parameters to the job that is triggered by the trigger. Quartz has some different trigger types, but the most used are Simpletrigger and Crontrigger.

Simpletrigger is a simple solution if we need to perform a job at a given moment or trigger a job at a given moment and then break for a certain amount of time, if we want to trigger a job based on a similar calendar schedule, say, Crontrigger is useful at every Friday noon or 10:15 trigger job on the 10th day of each month.

Why use jobs and triggers? Many task schedulers do not have the concept of tasks and triggers, and some task scheduler simply defines a "job" as a combination of some small tasks in one execution time, others more like quartz job and trigger objects. When developing the quartz, the developers decided that the schedule and the work to run on it should be separate. This is very useful.

For example, a job can be created and stored in a task scheduler independently of triggers, and many triggers can be associated with the same job. Another benefit of this loose coupling is that after the trigger associated with jobs is terminated, we can again configure jobs that remain in the scheduler, so that we can dispatch the jobs again without having to redefine them. We can also modify or replace a trigger that is associated with a job without redefining it.

When jobs and triggers were registered in the Quartz scheduler, they had a unique identifier. They can also be put into "groups", groups is used to organize the classification of jobs and triggers for future maintenance. The name of the job and trigger in a group must be unique, in other words, the full name of a job and trigger for their name plus the group name. If you set the group name to "NULL", the system automatically resets it to Scheduler.default_group

Scheduler needs to be instantiated before it can be used. An instance is typically created by schedulerfactory. Some users save an instance of factory in Jndi, but it may be simpler to initialize it directly, and then use that instance (see the example below).

After the scheduler is instantiated, it can start (start), pause (stand-by), Stop (shutdown). Note: After the scheduler is stopped, it cannot be restarted unless it is re-instantiated, and the trigger will not be triggered until scheduler is started, even if it is in a paused state (the job will be executed).


v. Introduction of Simpletrigger

As its name suggests, Simpletrigger is the simplest quartztrigger for setup and use. It is designed for a Job that needs to be started at a specific date/time and executes n times at a possible interval of time.
We have already used the Simpletrigger in a simple quartz example, we

Simpleschedulebuilder builder=simpleschedulebuilder.simpleschedule ()//Set interval execution time. Withintervalinseconds (5)// Sets the number of executions. Withrepeatcount (4);
Trigger Trigger=triggerbuilder.newtrigger (). Withidentity ("Trigger1_1", "TGroup1"). Startnow (). Withschedule ( Builder). Build ();

or infinite execution

Simpleschedulebuilder builder=simpleschedulebuilder.simpleschedule ()//Set interval execution time. Withintervalinseconds (5)//  Sets the number of executions. RepeatForever ();              Trigger Trigger=triggerbuilder.newtrigger (). Withidentity ("Trigger1_1", "TGroup1"). Startnow (). withschedu Le (builder). Build ();

For quartz, it does not satisfy our triggering situation, so it is only used for some simple triggering situations;

Liu, Crontrigger

Crontrigger allows a very complex trigger schedule to be set. Sometimes, however, you may have to use two or more simpletrigger to meet your triggering needs, and you just need a crontrigger instance. As the name implies, Crontrigger is a cron-like expression based on Unix. For example, you might have a Job that executes every five minutes between Monday and Friday morning 8:00-9:00. If you try to use Simpletrigger, you may want to configure multiple trigger for this Job. However, you can use the following expression to produce a Trigger that is triggered by this schedule;
Like what:


Create Triggercronschedulebuilder Builder2 = Cronschedulebuilder.cronschedule ("0 0/5 8 * * *");//8:00-8:55, execute/** every 5 minutes Builder2 = Cronschedulebuilder.dailyathourandminute (n), **/trigger Trigger=triggerbuilder.newtrigger (). Withidentity ("Trigger1_1", "TGroup1"). Startnow (). Withschedule (Builder2). build ();


because of the crontrigger built-in flexibility, it is also innate to create almost unlimited expressions, and because of the UNIX-enabled cron expression, as an enterprise application, our operating system is generally based on the Unxi operating system, So it is necessary to master the cost of Crontrigger, we will introduce the Crontrigger in detail later. The format of the cron expression is shown in the next section.

Vii. The relationship between job and trigger

As we all know, a job, the more important three elements is Schduler,jobdetail,trigger, and Trigger for the job is like a drive, there is no trigger to schedule the job, the job will not work, for the job, A job can correspond to multiple Trigger, but for Trigger, a Trigger can only correspond to one job; so a Trigger can only be assigned to a job; If you need a more complex trigger plan, you can create multiple Trigger and assign them to the same Job. Scheduler is based on the configuration of the job Trigger to determine the correct execution plan, the following is the use of multiple Trigger for the same jobdetail;


Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka




"Quartz" in-depth job, Jobdetail, Jobdatamap, Trigger

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.