Quartz Java-implemented Timing task framework

Source: Internet
Author: User
Tags numeric value ranges
Overview

Understanding the Quartz architecture

Quartz The problem of task scheduling in a highly abstract, the 3 core concepts of scheduler, task and trigger are presented, and the important core concepts are described through interfaces and classes in Org.quartz:

Job: Is an interface, there is only one method void execute (Jobexecutioncontext context), the developer implements the interface to define the running task, The Jobexecutioncontext class provides various information about the scheduling context. The information in the job runtime is stored in the Jobdatamap instance;

jobdetail: Quartz Creates a job instance every time the job is executed, so it does not accept an instance of a job directly, instead it receives a job implementation class so that the runtime passes the newinstance () Reflection mechanism to instantiate the job. Therefore, a class is needed to describe the implementation class of the job and other relevant static information, such as job name, description, associated listener and other information, Jobdetail assumed this role.

The constructor of the class can be more specific about its function: Jobdetail (java.lang.String name, java.lang.String Group, Java.lang.Class Jobclass), The constructor requires the implementation class for the specified job, and the group name and job name of the task in scheduler;

Trigger: Is a class that describes the time trigger rule that triggers a job execution. There are mainly two subclasses of Simpletrigger and Crontrigger. Simpletrigger is the most appropriate choice when it is only triggered once or at a fixed time interval, while Crontrigger can define a scheduling scheme with a variety of complex time rules through a cron expression: such as every 9:00, Monday, Wednesday, Friday afternoon 5:0 0 implementation, etc.;

Calendar : Unlike Org.quartz.Calendar and Java.util.Calendar, it is a collection of calendar-specific points of time (you can simply view Org.quartz.Calendar as a collection of Java.util.Calendar- Java.util.Calendar represents a calendar point of time, with no special description behind the calendar that refers to Org.quartz.Calendar). A trigger can be associated with multiple calendar to exclude or contain some point in time.

Suppose, we schedule a weekly Monday 10:00 to perform a task, but if we encounter a statutory holiday, the task is not executed, then we need to use calendar for the trigger trigger mechanism based on fixed point exclusion. For different time period types, Quartz provides several calendar implementation classes under the Org.quartz.impl.calendar package, such as Annualcalendar, Monthlycalendar, Weeklycalendar are defined for each year, month and week respectively;

Scheduler: Represents a quartz independent running container, trigger and Jobdetail can be registered in Scheduler, both of which have their own group and name in Scheduler, Groups and names are the basis for finding an object in a scheduler container, trigger groups and names must be unique, and jobdetail groups and names must be unique (but can be the same as trigger groups and names because they are of different types). Scheduler defines multiple interface methods that allow external access to and control of trigger and jobdetail in containers through groups and names.

Scheduler can bind trigger to a jobdetail so that when the trigger is triggered, the corresponding job is executed. A job can correspond to multiple trigger, but a trigger can only correspond to one job. You can create a scheduler instance from Schedulerfactory. Scheduler has a schedulercontext, similar to ServletContext, which holds scheduler context information, and both job and trigger can access the information within the Schedulercontext. Schedulercontext internally uses a map to maintain these contextual data in a key-value pair, Schedulercontext provides multiple put () and getxxx () methods for saving and fetching data. The corresponding Schedulercontext instance can be obtained by scheduler# GetContext ();

Threadpool:scheduler uses a thread pool as the infrastructure for the task to run, and the task increases the efficiency of the operation through threads in the shared thread pool.

The job has a statefuljob sub-interface that represents a stateful task, which is a label interface with no methods, and its purpose is to let quartz know the type of task in order to adopt different execution scenarios. Stateless tasks have their own jobdatamap copies at execution time, and changes to Jobdatamap do not affect the next execution. While stateful task sharing shares the same Jobdatamap instance, the changes that are made to Jobdatamap each time the task executes are saved, and subsequent execution can see the change, which affects subsequent execution after each execution of the task.

For this reason, stateless jobs can be executed concurrently, and stateful statefuljob cannot be executed concurrently, which means that if the previous Statefuljob has not been completed, the next task will block the wait until the previous task has finished executing. Stateful tasks have more factors to consider than stateless tasks, and programs tend to have a higher degree of complexity, so you should try to use stateless jobs unless necessary.

If Quartz uses database persistence task scheduling information, stateless Jobdatamap will only be maintained once while Scheduler registers the task, and the status task corresponds to the jobdatamap is saved every time the task is executed.

Trigger itself can also have a jobdatamap, whose associated job can be obtained by Jobexecutioncontext#gettrigger (). Getjobdatamap () the jobdatamapin the Trigger. Whether stateful or stateless, changes made to Trigger 's jobdatamap during the execution of a task do not persist, nor do they affect the next execution.

Quartz has a perfect event and monitoring system, most components have events, such as task before the event, after the task after the execution of events, triggers before the trigger event, triggered events, scheduler start events, shutdown events, etc., you can register the appropriate listener to handle the event of interest.

Figure 1 depicts the internal component structure of the Scheduler ,schedulercontext provides Scheduler globally visible context information, each of which corresponds to a Jobdatamap, a dashed expression of Jobdatamap represents a task of due status:

Fig. 1 Scheduler structure diagram

A scheduler can have multiple Triger groups and multiple jobdetail groups, and when registering trigger and jobdetail, if you do not explicitly specify the group to which it belongs, Scheduler is placed in the default group, The group name for the default group is Scheduler.default_group. Group names and names make up the full name of the object, and the full name of the same type of object cannot be the same.

The scheduler itself is a container that maintains the various components of the quartz and implements the rules of dispatch. Scheduler also has a thread pool, which provides execution threads for tasks-which is more efficient than simply creating a new thread when performing a task, while sharing a resource-saving footprint. With the support of thread pool component, quartz can provide good scalability for task scheduling with high peak and pressure.

Tip: Quartz full Download Package Examples directory has more than 10 instances, they are a quick grasp of the quartz application is a good example. using Simpletrigger

Simpletrigger has multiple overloaded constructors to construct a corresponding instance in different situations:

Simpletrigger (string name, String group): This constructor specifies the group and name to which trigger belongs;

Simpletrigger (string name, String group, Date starttime): In addition to specifying the group and name to which trigger belongs, you can specify the development time that is triggered;

Simpletrigger (string name, string group, date starttime, date endtime, int repeatcount, long repeatinterval): In addition to specifying the above information, you can also To specify the end time, repeated execution times, time interval, and other parameters;

Simpletrigger (string name, String group, String jobName, String jobgroup, date starttime, date endtime, int repeatcount, Long repeatinterval: This is one of the most complex constructors, which, while specifying the triggering parameters, also associates the trigger with a task in scheduler through Jobgroup and JobName.

By implementing Org.quartz ... Job interface, which enables the Java class to be transformed into a scheduled task. Code Listing 1 provides an example of a Quartz task:

Code Listing 1 Simplejob: A simple job implementation class

<span style= "Background-color:rgb (255, 255, 255);" ><span style= "Background-color:rgb (255, 255, 204);" >package Com.baobaotao.basic.quartz;

Import java.util.Date;

Import Org.quartz.Job;

Import Org.quartz.JobExecutionContext;

Import org.quartz.JobExecutionException;

Public class Simplejob implements job {

① Instance Job interface method public

void execute (jobexecutioncontext jobctx) throws jobexecutionexception {

System.out.println (Jobctx.gettrigger (). GetName () + triggered. Time is: "+ (new Date ());

}

} </span></span>

This class implements the Execute (Jobexecutioncontext context) method of the job interface with a very simple output statement, which can contain any code that you want to execute. Below, we dispatch the Simplejob via Simpletrigger:

Code Listing 2 Simpletriggerrunner: Scheduling with Simpletrigger

<span style= "Background-color:rgb (255, 255, 255);" ><span style= "Font-family:simsun; font-size:10px; Background-color:rgb (255, 255, 204);

>package Com.baobaotao.basic.quartz;

Import Java.util.Date;

Import Org.quartz.JobDetail;

Import Org.quartz.Scheduler;

Import Org.quartz.SchedulerFactory;

Import Org.quartz.SimpleTrigger;

Import Org.quartz.impl.StdSchedulerFactory; public class Simpletriggerrunner {public static void main (String args[]) {try {①) creates a Jobdetail instance, specifying Simplejob Jobdeta

Il jobdetail = new Jobdetail ("Job1_1", "JGroup1", Simplejob.class); ② defines the scheduling rule by Simpletrigger: Start immediately, run every 2 seconds, run 100 times Simpletrigger Simpletrigger = new Simpletrigger ("Trigger1_1", "Tgroup1")

;

Simpletrigger.setstarttime (New Date ());

Simpletrigger.setrepeatinterval (2000);

Simpletrigger.setrepeatcount (100);

③ obtains a scheduler instance via schedulerfactory schedulerfactory schedulerfactory = new Stdschedulerfactory ();

Scheduler Scheduler = Schedulerfactory.getscheduler (); Scheduler.schedulejob (Jobdetail,Simpletrigger); ④ registration and scheduling Scheduler.start (); ⑤ dispatch startup} catch (Exception e) {e.printstacktrace (); }}}</span></span>


First, the Jobdetail encapsulates simplejob at ① and specifies the group and name of the job in scheduler, where the group name is JGroup1, and the name is Job1_1.

Create a Simpletrigger instance at ② to specify the group and name that the trigger belongs to in scheduler. Then set the scheduling time rule.

Finally, you need to create a scheduler instance and register the Jobdetail and trigger instances into scheduler. Here, we get a scheduler instance through Stdschedulerfactory and do two things through Schedulejob (Jobdetail jobdetail, Trigger Trigger):

1 Registration of Jobdetail and trigger into scheduler;

2) Assign trigger to Jobdetail and associate the two.

When scheduler is started, trigger periodically triggers and executes the simplejob execute (jobexecutioncontext jobctx) method, and then repeats every 10 seconds until the task is executed 100 times before stopping.

You can also specify a running time range through the Simpletrigger setstarttime (java.util.Date starttime) and Setendtime (Java.util.Date endtime). Tasks that exceed the time range are not executed when the number of runs and time ranges conflict. You can start after 60 seconds by specifying Simpletrigger.setstarttime (New Date (System.currenttimemillis () + 60000L)).

In addition to establishing trigger and jobdetail associations through Schedulejob (Jobdetail, Simpletrigger), there is another way of associating Trigger and Jobdetail:

<span style= "Background-color:rgb (255, 255, 255);" ><span style= "Font-family:simsun; font-size:10px; Background-color:rgb (255, 255, 204); >jobdetail jobdetail = new Jobdetail ("Job1_1", "JGroup1", simplejob.class);

Simpletrigger Simpletrigger = new Simpletrigger ("Trigger1_1", "Tgroup1");

... Simpletrigger.setjobgroup ("JGroup1"); ①-1: Specify the associated job group name

simpletrigger.setjobname ("job1_1"); ①-2: Specify the associated job name

Scheduler.addjob (Jobdetail, True); ② registered Jobdetail

scheduler.schedulejob (simpletrigger); ③ REGISTRATION Specifies the trigger</span></span> of the associated Jobdetail


In this way, Trigger registers Trigger by specifying the group and job name that the job belongs to, and then using the Scheduler Schedulejob (Trigger Trigger) method. There are two notable places to watch:

The trigger instance registered in this manner must have already specified the job group and job name, otherwise the method that calls the registration trigger throws an exception;

The referenced Jobdetail object must already exist in the scheduler. In other words, the sequence of ①, ② and ③ in the code is not interchangeable.

When you construct a trigger instance, consider using the Org.quartz.TriggerUtils tool class, which not only provides a number of methods for obtaining a specific time, but also has numerous methods for obtaining common trigger, such as Makesecondlytrigger ( The string Trigname method creates a trigger that executes once per second, while Makeweeklytrigger (string trigname, int dayofweek, int hour, int minute) A trigger will be created one at a specific point in time every week. The Getevenminutedate (date date) method returns a minute after a point in time. using Crontrigger

Crontrigger can provide more specific scheduling scenarios than Simpletrigger, scheduling rules based on Cron expressions, Crontrigger support calendar-related repeat intervals (such as the first Monday of the month), rather than simple cycle intervals. As a result, Crontrigger is more complex to use than Simpletrigger. Cron Expression

Quartz uses a cron expression like Linux to define a time rule that consists of 6 or 7 time fields separated by spaces, as shown in table 1:

Table 1 Cron Expression Time field

6

Position

Time domain name

Allow values

Allowed special characters

1

sec

0-59

,-*/

2

min

0-59

,-*/

3

Hours

0-23

,-*/

4

Date

1-31

,-*?/L W C

Week

1-7

,-*?/L C #

7

Year (optional)

null 1970-2099

,-*/

The time field of a cron expression allows you to set a numeric value, and you can use special characters to provide lists, ranges, wildcard characters, and so on, as follows:

Asterisk (*): Used in all fields to represent every moment of the corresponding time field, for example, * "Per minute" in the minute field;

Question mark (?): The character is used only in the date and week fields, which is usually specified as "meaningless value", equivalent to a bit character;

Minus sign (-): expresses a range, such as using "10-12" in the hour field, representing 10 to 12 points, i.e. 10,11,12;

Comma (,): Expresses a list value, such as "Mon,wed,fri" in the Week field, for Monday, Wednesday, and Friday;

Slash (/): X/y expresses a sequence of equal steps, X is the starting value, and Y is the increment step value. If you use 0/15 in the minute field, it is 0,15,30 and 45 seconds, and 5/15 represents 5,20,35,50 in the minute field, you can also use */y, which is equivalent to 0/y;

L: This character is used only in the date and week fields, meaning "last", but it means different in two fields. L In the Date field, represents the last day of the month, such as number 31st in January, not leap year February 28th; if L is used in the week, it means Saturday, equivalent to 7. However, if L appears in the Week field and has a value x in front of it, it means "last x days of the Month", for example, 6L represents the last Friday of the month;

W: This character can only appear in the Date field and is a cosmetic of the leading date that represents the most recent weekday from that date. For example, 15W represents the most recent working day from 15th, if the month 15th is Saturday, match 14th Friday; if 15th is Sunday, match 16th Monday; if 15th is Tuesday, the result is 15th Tuesday. But it must be noted that the associated matching date is not able to span the month, as you specify 1W, if number 1th is Saturday, the result matches the number 3rd Monday, not last month. The W string can only specify a single date and cannot specify a date range;

LW combination: In the Date field can be combined to use LW, which means the last working day of the month;

Pound sign (#): This character can only be used in the week field, indicating a weekday of the month. If 6#3 said that the third Friday of the month (6 for Friday, #3表示当前的第三个), and 4#5 that the month of the fifth Wednesday, assuming that the month does not have the fifth Wednesday, ignoring the trigger;

C: This character is used only in the date and week fields and represents the meaning of calendar. It means the date that the plan is associated with, and if the date is not associated, it is equivalent to all the dates in the calendar. For example 5C in the Date field corresponds to the first day of the calendar after 5th. 1C is equivalent to the first day after Sunday in the Week field.

Cron expressions are not sensitive to the case of special characters, nor are they sensitive to the abbreviated English case of the representative week.

Table 2 shows some examples of the complete cron representation:

Table 2 Example of a cron representation

Representation of

Description

"0 0 12 * *?"

Run at 12 every day.

"0 15 10?" * *"

Run 10:15 every day

"0 15 10 * *?"

Run 10:15 every day

"0 15 10 * *? *"

Run 10:15 every day

"0 15 10 * *? 2008 "

Running 10:15 every day in 2008.

"0 * 14 * *?"

Run every minute between 14 o'clock and 15 every day, starting at 14:00 and ending at 14:59.

"0 0/5 14 * *?"

Run every 5 minutes from 14 o'clock to 15 every day, starting at 14:00 and ending at 14:55.

"0 0/5 14,18 * *?"

Run every 5 minutes from 14 o'clock to 15 every day, and also every 5 minutes every 18 o'clock to 19 o ' clock.

"0 0-5 14 * *?"

Every day 14:00 to 14:05, run every minute.

"0 10,44 14?" 3 WED "

March every Wednesday of 14:10 minutes to 14:44, run every minute.

"0 15 10?" * Mon-fri "

Run for 10:15 minutes per Monday, two, three, four, five.

"0 15 10 15 *?"

Every month 15th 10:15 minutes run.

"0 L *?"

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.