Quartz learning and implementation under spring

Source: Internet
Author: User
Tags constructor

Quartz is the point of the Open Source task scheduling framework and provides a powerful task scheduling mechanism. Typical enterprise application scheduling, such as the forum: every half an hour to generate the essence of the article rss, every morning to count the user's points ranking.

The above-mentioned scheduling scenario core is to focus on the point of time scheduling, in fact, also includes resource scheduling. For example, when a Web server receives a request, it immediately creates a new thread to service the request, which is also the scope of the dispatch.

Quartz is highly abstracted from the scheduling scenario, and proposes three core concepts, Scheduler-scheduler, Task-job, and trigger-trigger.

http://www.blogjava.net/baoyaer/articles/155645.html article good, recommended. 1. Scheduler-job Source code: Visible job is just an interface, there is execute () This method, in the implementation class by implementing the Execute () method to represent the task to be performed

Package Org.quartz;
 /** * <p> * The interface to being implemented by classes which represent a ' job ' to be * performed. * </p> * * <p> * Instances of <code>Job</code> must have a <code>public</code> *
 No-argument constructor. * </p> * * <p> * <code>JobDataMap</code> provides a mechanism for ' instance member data ' * th
 At May is required by some implementations of this interface. * </p> * * @see jobdetail * @see statefuljob * @see Trigger * @see Scheduler * * @author James House */PU 
     Blic interface Job {/* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
     * Interface.
     * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *//** * <p> * Called by the <code>{@link scheduler}</code> when a <code>{@link trigger}</code> * Fires t Hat is associated with the <Code>job</code>. * </p> * * <p> * The implementation wish to set a * {@link jobexecutioncontext#setre  Sult (object) result} Object on the * {@link Jobexecutioncontext} before this method exits. The result itself * is meaningless to Quartz and may be informative to * <code>{@link joblistener}s</
     code> or * <code>{@link triggerlistener}s</code> that is watching the job ' s * execution. * </p> * * @throws jobexecutionexception * If there is a exception while executing the J
     Ob.

*/void Execute (Jobexecutioncontext context) throws jobexecutionexception; }

2. Task Details-jobdetailThe following is the source Code copy Acquisition section, the Jobdetail constructor indicates that the job instance object is managed by the job in the scheduler by the group name and job name. One word the implementation object for the Jobdetail class management job.
Public Jobdetail (string name, String group, Class jobclass) {
        setName (name);
        Setgroup (group);
        Setjobclass (Jobclass);
    }

3. Trigger-trigger

A diagram to help you understand the trigger, personal feeling or Crontrigger implementation class use more widely, the following project demo is to use this subclass.
4. Scheduler-schedulerRepresents a quartz standalone run container, trigger-triggers and jobdetail-task details can be registered to scheduler, and both have their own separate groups and names. One blog post is more practical, http://blog.csdn.net/hongweigg/article/details/6185599, and tells you that you may encounter blocking problems when using quartz. I combine quartz code to understand, hope to useful friends can help.
Structure diagram:

Job sub-interface Statefuljob source code:
/* Copyright 2001-2009 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); The * use of this file except-compliance with the License.  Obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required  By applicable-law or agreed-to-in writing, software * Distributed under the License are distributed on a "as is" BASIS, Without * warranties or CONDITIONS of any KIND, either express or implied.
 See the * License for the specific language governing permissions and limitations * under the License.

* * * Package org.quartz; /** * <p> * A marker interface for <code>{@link org.quartz.jobdetail}</code> s It * wish to has th
 EIR state maintained between executions. * </p> * * <p> * <code>StatefulJob</code> instances follow slightly different rules from * RE Gular <code>Job</code> instances. The key difference is thAt their * Associated <code>{@link jobdatamap}</code> was re-persisted after every * execution of the job, th US preserving state for the next execution. The * Other difference was that stateful jobs was not allowed to execute * Concurrently, which means new triggers that OC
 Cur before the completion of * the <code>execute (XX) </code> method would be delayed. * </p> * * @see Job * @see jobdetail * @see jobdatamap * @see Scheduler * * @author James House */Public Interface Statefuljob extends Job {/* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     ~ ~ * * Interface.
 * 
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

}

Job at run time information will be saved in Jobdatamap, usually when the job executes, the default is to perform a stateless job, each instance object will have a separate JOBDATAMAP replication, changes to Jobdatamap will not affect the next execution, so a stateless job can execute concurrently. Statefuljob represents a stateful job that shares the same jobdatamap, and each time a task executes a change to Jobdatamap is saved, so A stateful job cannot execute concurrently。 Only the last Statefuljob execution completes the next statefuljob to execute, otherwise it will block the wait. In spring, the concurrent zodiac can be used to indicate that there is no state, concurrent=true indicates concurrency, and false indicates that it cannot be concurrent. This is reflected in the demo below. When the interface network is busy, the Interface status Query task takes a long time, and the spring scheduled task is executed concurrently by default and does not wait for the last task execution to finish, as long as the interval is over. The interface Status Query task executes every 5 minutes, and if it executes for 1 hours each time, other tasks are blocked. Because quartz threads are consumed by the interface State Query task. Other tasks are only waiting. -------------first Remember, in case you can use it. ########################################################################################################### ##########
1. Maven Library with quartz
<dependency>
			  <groupId>org.quartz-scheduler</groupId>
			  <artifactid>quartz</ artifactid>
			  <version>1.8.4</version>
		</dependency>


configuration file for 2.Quartz2.1. First introduce the configuration file in Web. XML sample-job.xml



2.2.sample-job.xml configuration file:
<!--Task Scheduler executes once every 2 seconds--<!--work class to invoke--<bean id= "Quartzjob" class= "Com.suning.sample.job.QuartzJob" /> <!--define methods for calling objects and calling objects--<bean id= "Jobdetail" class= "Org.springframework.scheduling.quartz.MethodInvok Ingjobdetailfactorybean "> <!--called Class-<property name=" TargetObject "> <ref bean=" quartzjob "/ > </property> <!--calling methods in classes--<property name= "Targetmethod" > <value>work</valu E> </property> <!--true: can be concurrent or not concurrent--<property name= "concurrent" > <value>true </value> </property> </bean> <!--define trigger time-<bean id= "Dotime" class= "Org.springframewo Rk.scheduling.quartz.CronTriggerBean "> <property name=" jobdetail "> <ref bean=" jobdetail "/> </pro Perty> <!--delay Trigger--<property name= "Startdelay" > <value>3000</value> &LT;/PROPERTY&G
		T <!--cron expression--&Gt <property name= "Cronexpression" > &LT;VALUE&GT;0/2 * * * *?</value> </property> </bean> & lt;! ---General management class if you lazy-init= ' false ' then the container starts executing the scheduler--<bean id= "Startquertz" lazy-init= "false" autowire= "no" class= "org . Springframework.scheduling.quartz.SchedulerFactoryBean "> <property name=" triggers "> <list> <re F bean= "Dotime"/> </list> </property> </bean>


2.2.1:methodinvokingjobdetailfactorybean

To meet the specifications of the quartz job interface, a class implementation job interface is required, overriding the Execute () method to define the method that needs to be dispatched, and then jobdetail to manage the job's implementation class through the construction method, which does not conform to spring's injection style. I really like the spring injection method of set. So spring uses the Methodinvokingjobdetailfactorybean class to manage the beans to be dispatched. There are two important property,targetobject and targetmethod that represent the classes and methods to invoke, so that you can write directly to the bean that you want to dispatch without having to implement the job interface.
The Concurrent property indicates whether the Quartzjob#work () method can be concurrent and defaults to true. True: Represents concurrency, false: not concurrent.
2.2.2: Create TRIGGER-triggerThere are two implementation classes, Simpletriggerbean and Crontriggerbean, which support cron notation to define the trigger time, as described earlier. The important property is Jobdetail and Cronexpression. The cron time expression rules are described below:
2.2.3:cron Expression Rules Quartz defines a time rule using a cron expression similar to Linux, and a cron expression consists of 6 or 7 space-delimited time fields, as shown in table 1:

Table 1:cron expression Time field

4

7

Location

Time domain name

Allowed value

Allowed special characters

1

sec

0-59

,-*/

2

Minutes

0-59

,-*/

3

hrs

0-23

,-*/

Date

1-31

,-*?/L W C

5

Month

1-12

,-*/

6

Week

1-7

,-*?/L C #

Year (optional)

Null value 1970-2099

,-*/

The time field of a cron expression, in addition to allowing you to set a value, can also use some special characters, such as lists, scopes, wildcards, and so on:

Asterisk (*): Available in all fields, representing every moment of the corresponding time field, for example, * in the minute field, means "per minute";

Question mark (?): This character is used only in date and weekday fields, and it is usually specified as "meaningless value", which is equivalent to a dot character;

Minus sign (-): expresses a range, such as the use of "10-12" in the hour field, that is, from 10 to 12 points, that is, 10,11,12;

Comma (,): Expresses a list value, such as "Mon,wed,fri" in the day of the week field, that is, Monday, Wednesday, and Friday;

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

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

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

LW combination: In the Date field can be combined using 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 represents the third Friday of the month (6 indicates Friday, #3表示当前的第三个), and 4#5 represents the fifth Wednesday of the month, assuming that the month does not have fifth Wednesday, ignoring does not trigger;

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

Cron expressions are insensitive to the case of special characters, and are not sensitive to the case of the abbreviated English-language representation of the week.


Table 2 shows some examples of the complete cron expression:

Table 2 Cron Expression Examples

Expression

Description

"0 0 12 * *?"

Runs at 12 o ' Day

"0 15 10?" * *"

Run 10:15 Daily

"0 15 10 * *?"

Run 10:15 Daily

"0 15 10 * *?" *"

Run 10:15 Daily

"0 15 10 * *?" 2008 "

Runs 10:15 every day in 2008.

"0 * 14 * *?"

It runs every minute from 14 o'clock to 15, starts at 14:00 and ends 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 * *?"

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

"0 0-5 14 * *?"

It runs every minute from 14:00 to 14:05.

"0 10,44 14?" 3 WED "

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

"0 15 10?" * Mon-fri "

Every Monday, two, three, four, five of 10:15 minutes run.

"0 15 10 15 *?"

Run every 15th 10:15.

"0 L *?"

Run 10:15 on the last day of each month.

"0 15 10?" * 6L "

Run the last month of Friday 10:15.

"0 15 10?" * 6L 2007-2009 "

Run 10:15 minutes in the last Friday of the month of the 2007,2008,2009 year.

"0 15 10?" * 6#3 "

Run for the third Friday month of 10:15 minutes.



3.quartzjob-The class being called
Package com.suning.sample.job;

Import java.util.Date;

/**
 * * 
 dispatched task class <br> 
 *〈 function Detailed description
 *
 * @author 13073386
 * @see [Related Classes/methods] (optional)
 * @since [Product /module Version] (optional) */public
class Quartzjob {public
    void work () {
        System.out.println ("It begins to job" + " ("+ new Date () +") ");
    }

}

4. The result of the implementation -2s called once

The cron rule is called once in two seconds, depending on the actual demand.

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.