Introduction to the use of Quatz clustered timed tasks

Source: Internet
Author: User

Profile

The main introduction quartz how to use, the principle please read the following references, collation has been very detailed. The primary purpose of using a quartz cluster is to avoid a single-point job failure, which is automatically re-executed after a critical job failure.

User Guide

    • Join Quartz Jar Package Dependency

<dependency>    <groupId>com.opensymphony.quartz</groupId>    <artifactId> Com.springsource.org.quartz</artifactid>    <version>1.6.2</version></dependency>

    • Integrated Spring configuration (Spring 3.2.x)

<bean id= "Schedulerfactorybean" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" > < Property Name= "Configlocation" value= "Classpath:quartz.properties"/> <!--set to auto-start--<property name= "aut Ostartup "value=" true "/> <!--this name was persisted as Sched_name in db. For local testing could change to unique name to avoid collision with Dev server--<property name= "Schedulernam E "value=" Quartzscheduler "/> <!--optional, update your existing job Quartzscheduler start-up, so you don't have to delete targetobject every time you modify Qrtz_job_ The details table corresponds to <property name= "Overwriteexistingjobs" value= "true"/> <!--required, Quartzscheduler delay start, application restart After the Quartzscheduler is activated---<property name= "Startupdelay" value= "/>" <property name= applicationcontext Schedulercontextkey "value=" ApplicationContext "/> <!--registration Trigger--<property name=" triggers "> &L t;list> <ref local= "Demojobtrigger"/> </list> </Property></bean><bean id= "Demojobdetail" class= "Org.springframework.scheduling.quartz.JobDetailBean" > <property name= "name" value= "Demojobdetailname"/> <property name= "group" value= "Demojobdetailgroup"/&G    T <property name= "jobclass" value= "org. Acrusher.demojobclass "/> <!--Requestsrecovery property is true, when the quartz service is aborted, starting the task again will attempt to resume all tasks that were not completed before-< Property Name= "Requestsrecovery" value= "false"/> <!--identity job is persistent, deleting all triggers without deleting them--<property name= "Durab Ility "value=" true "/> <!--is staged, if, re-starting quartz not present--<property name=" volatility "value=" false "/></bean><bean id=" Demojobtrigger "class=" Org.springframework.scheduling.quartz.CronTriggerBean " > <property name= "name" value= "Demojobtriggername"/> <property name= "group" value= "Demojobtriggergroup"/ > <property name= "jobdetail" ref= "Demojobdetail"/> <property name= "cronexpression" value= "0 0 1 * *? * "/&GT;&LT;/bean> 

    • Configure Quartz.properties
# Using Spring DataSource in quartzjobsconfig.xml# Spring uses localdatasourcejobstore extension of jobstorecmt# Org.quart z.jobstore.useproperties=trueorg.quartz.jobstore.tableprefix=qrtz_org.quartz.jobstore.isclustered=true# 10 secondsorg.quartz.jobstore.clustercheckininterval=10000org.quartz.scheduler.skipupdatecheck=true# change this to Match your DB Vendororg.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.jobstoretxorg.quartz.jobstore.driverdelegateclass= org.quartz.impl.jdbcjobstore.stdjdbcdelegate# Needed to manage cluster instancesorg.quartz.scheduler.instanceid= autoorg.quartz.scheduler.instancename=demo_job_schedulerorg.quartz.scheduler.rmi.export= falseorg.quartz.scheduler.rmi.proxy=falseorg.quartz.threadpool.class= org.quartz.simpl.simplethreadpoolorg.quartz.threadpool.threadcount=10org.quartz.threadpool.threadpriority= 5org.quartz.threadpool.threadsinheritcontextclassloaderofinitializingthread=trueorg.quartz.jobstore.datasource =mydsorg.quartz.datasource.myds.driver=com.mysQl.jdbc.driverorg.quartz.datasource.myds.url=${org.quartz.datasource.myds.url}org.quartz.datasource.myds.user= ${org.quartz.datasource.myds.user}org.quartz.datasource.myds.password=${org.quartz.datasource.myds.password} org.quartz.datasource.myds.maxconnections=5org.quartz.jobstore.misfirethreshold=120000

    • Writing Demojobclass

Import Org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;import Org.slf4j.Logger;import Org.slf4j.loggerfactory;import Org.springframework.context.applicationcontext;import Org.springframework.scheduling.quartz.quartzjobbean;import Java.io.serializable;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.util.concurrent.TimeUnit Import java.util.concurrent.locks.reentrantlock;/** * Cluster Job abstract class * <p/> * Created by Acrusher on 2016/4/7. */public abstract class Abstractclusterjob extends Quartzjobbean implements Serializable {protected static final Logge    R logger = Loggerfactory.getlogger ("Quartzjob");    Private static final long serialversionuid = 3158445449885064827L; Protected ApplicationContext applicationcontext;//is automatically injected by the parent class.    Note that Quartzjobbean will only inject the spring context. public void Setapplicationcontext (ApplicationContext applicationcontext) {this.applicationcontext = ApplicationCon    Text } @Override protected void Executeinternal (Jobexecutioncontext context) throws Jobexecutionexception {Long start = System        . Currenttimemillis (); Logger.warn (">>> Cluster Job Frame |        jobclass:{} started. ", GetClass (). Getsimplename ());            try {beforejob ();        Run (context); } catch (Exception e) {logger.error ("jobclass:{} |        jobcontext:{} ", New Object[]{getclass (). Getsimplename (), Context, e}); } finally {Logger.warn (">>> Cluster Job Frame | jobclass:{} finished.        Costtime:{}ms ", GetClass (). Getsimplename (), System.currenttimemillis ()-start);    }}//job business logic protected abstract void Run (Jobexecutioncontext context); Inject the necessary bean protected void beforejob () throws invocationtargetexception before job execution, illegalaccessexception {//init i        Njection, etc method[] Methods=getclass (). Getdeclaredmethods ();            for (Method m:methods) {m.setaccessible (true); if (M.GEtname (). StartsWith ("set")) {String name=m.getname (). substring (3);                if (Name.length () >1) {name=character.tolowercase (Name.charat (0)) +name.substring (1);                }else {name=string.valueof (character.tolowercase (Name.charat (0)));                    } try {Object bean = Applicationcontext.getbean (name);                    if (bean! = null &&!bean.equals ("ApplicationContext")) {M.invoke (this, bean);                }}catch (Exception e) {logger.error ("", e); }            }        }    }}

    • Write a specific business job
Import org.quartz.jobexecutioncontext;/** * Created by Acrusher on 2016/4/7. */public class Demojobclass extends Abstractclusterjob {    private static final long Serialversionuid = 694541474361182 9056L;        Private Usermanager Usermanager;        @Override    protected void Run (Jobexecutioncontext context) {        //Some Biz code ...    }    Automatically injected by the parent class public    void Setusermanager (Usermanager usermanager) {        This.usermanager = Usermanager;    }}

    • Tables to be used in MySQL to generate quartz
CREATE TABLE ' qrtz_job_details ' (' job_name ' varchar) NOT NULL, ' job_group ' varchar ($) NOT null, ' DESCRIPTION ' varchar (+) DEFAULT null, ' job_class_name ' varchar (+) NOT null, ' is_durable ' varchar (1) is not NULL, ' is_volatile ' varchar (1) Not NULL, ' is_stateful ' varchar (1) is not NULL, ' requests_recovery ' varchar (1) is not NULL, ' Job_data ' BLOB, PRIMARY KEY (' Job_ NAME ', ' Job_group ')) engine=innodb DEFAULT charset=utf8; create TABLE ' qrtz_job_listeners ' (' job_name ' varchar ( ) not NULL, ' job_group ' varchar ($) NOT null, ' job_listener ' varchar ($) Not null,primary KEY (' job_name ', ' Job_group ' , ' Job_listener '), key ' job_name ' (' job_name ', ' Job_group '), CONSTRAINT ' Qrtz_job_listeners_ibfk_1 ' FOREIGN KEY (' Job_ NAME ', ' job_group ') REFERENCES ' qrtz_job_details ' (' job_name ', ' Job_group ')) Engine=innodb DEFAULT charset=utf8  CREATE TABLE ' qrtz_locks ' (' lock_name ' varchar (+) not null,primary KEY (' Lock_name ')) Engine=innodb DEFAULT Charset=utf8  create TABLE ' Qrtz_paused_trigger_grps ' (' TRIGGER_group ' varchar ($) Not NULL, PRIMARY KEY (' Trigger_group ')) engine=innodb DEFAULT charset=utf8 create TABLE ' qrtz_ Scheduler_state ' (' instance_name ' varchar) NOT NULL, ' Last_checkin_time ' bigint (all) not null, ' Checkin_interval ' BigInt () Not null,primary KEY (' instance_name ') Engine=innodb DEFAULT charset=utf8 create TABLE ' qrtz_triggers ' (' trigger_name ' varchar () not NULL, ' trigger_group ' varchar ($) NOT null, ' job_name ' varchar ($) NOT NULL, ' Job_group ' varchar ' is not NULL, ' is_volatile ' varchar (1) is not NULL, ' DESCRIPTION ' varchar (+) DEFAULT NULL, ' Next_fire_time ' bigint (+) default NULL, ' Prev_fire_time ' bigint (all) default NULL, ' priority ' int (one-by-one) default null, ' Trigger_state ' varchar (+) NOT null, ' trigger_type ' varchar (8) is not NULL, ' Start_time ' bigint (all) not null, ' End_time ' bigint (All) DEFAULT NU LL, ' calendar_name ' varchar ($) default null, ' Misfire_instr ' smallint (2) default null, ' Job_data ' blob,primary KEY (' Trigger_name ', ' Trigger_group '), KEY ' job_name ' (' job_name ', ' JOb_group '), CONSTRAINT ' Qrtz_triggers_ibfk_1 ' FOREIGN KEY (' job_name ', ' job_group ') REFERENCES ' qrtz_job_details ' (' JOB _name ', ' Job_group ')) engine=innodb DEFAULT charset=utf8 create TABLE ' qrtz_trigger_listeners ' (' trigger_name ' varchar (+) NOT null, ' trigger_group ' varchar ($) NOT null, ' trigger_listener ' varchar ($) Not null,primary KEY (' Trigger_name ', ' trigger_group ', ' Trigger_listener '), KEY ' trigger_name ' (' trigger_name ', ' Trigger_group '), CONSTRAINT ' Qrtz_trigger_listeners_ibfk_1 ' FOREIGN KEY (' trigger_name ', ' trigger_group ') REFERENCES ' qrtz_triggers ' (' Trigger_ NAME ', ' Trigger_group ')) engine=innodb DEFAULT charset=utf8 create TABLE ' qrtz_simple_triggers ' (' trigger_name ' varchar (+) is not null, ' trigger_group ' varchar ($) NOT null, ' Repeat_count ' bigint (7) is not NULL, ' Repeat_interval ' bigint ( Not NULL, ' times_triggered ' bigint (Ten) Not null,primary key (' trigger_name ', ' trigger_group '), key ' trigger_name ' (' Trigger_name ', ' Trigger_group '), CONSTRAINT ' Qrtz_simple_triggers_ibfk_1 ' FOREIGN KEY (' trigger_name ', ' trigger_group ') REFERENCES ' qrtz_triggers ' (' trigger_name ', ' Trigger_group ')) engine= InnoDB DEFAULT charset=utf8 create TABLE ' qrtz_blob_triggers ' (' trigger_name ' varchar () not NULL, ' Trigger_ GROUP ' varchar ' is not NULL, ' Blob_data ' blob,primary key (' trigger_name ', ' trigger_group '), key ' trigger_name ' (' Trigger_name ', ' Trigger_group '), CONSTRAINT ' Qrtz_blob_triggers_ibfk_1 ' FOREIGN KEY (' trigger_name ', ' Trigger_group ') REFERENCES ' qrtz_triggers ' (' trigger_name ', ' Trigger_group ')) engine=innodb DEFAULT charset=utf8 create TABLE ' Qrtz_calendars ' (' calendar_name ' varchar () not NULL, ' CALENDAR ' blob not NULL, PRIMARY KEY (' Calendar_name ')) engine=in Nodb DEFAULT charset=utf8create TABLE ' qrtz_cron_triggers ' (' trigger_name ' varchar () not NULL, ' Trigger_group ' varchar (+) NOT null, ' cron_expression ' varchar (+) NOT null, ' time_zone_id ' varchar ' DEFAULT null,primary KEY (' Trigger_name ', ' Trigger_group '), KEY ' trigger_name ' (' trigger_name ', ' TriggeR_group '), CONSTRAINT ' Qrtz_cron_triggers_ibfk_1 ' FOREIGN KEY (' trigger_name ', ' trigger_group ') REFERENCES ' qrtz_ TRIGGERS ' (' trigger_name ', ' Trigger_group ')) engine=innodb DEFAULT charset=utf8 create TABLE ' qrtz_fired_ TRIGGERS ' (' entry_id ' varchar) not NULL, ' trigger_name ' varchar ($) NOT null, ' trigger_group ' varchar ($) NOT NULL, ' Is_volatile ' varchar (1) NOT NULL, ' instance_name ' varchar ($) NOT null, ' Fired_time ' bigint (all) not NULL, ' priority ' int ( One) not NULL, ' state ' varchar (+) NOT null, ' job_name ' varchar ($) default null, ' Job_group ' varchar ($) default NULL, ' Is_ STATEFUL ' varchar (1) default null, ' requests_recovery ' varchar (1) default NULL, PRIMARY KEY (' entry_id ')) Engine=innodb DE FAULT Charset=utf8 insert into qrtz_locks values (' calendar_access ') INSERT into qrtz_locks values (' job_access ') I Nsert into qrtz_locks values (' misfire_access ') insert into qrtz_locks values (' state_access ') insert into Qrtz_locks VA Lues (' trigger_access ')  
Summarize

To this end of all configuration, the rest is the specific business Jobbean development. When deployed on multiple machines, each job is dynamically assigned to execute on a single machine. If the job is critical, a restart is required after the failure, or you can configure

Requestsrecovery is true to achieve task re-run. easy to avoid single point of failure and task abnormal unrecoverable problem.

Reference documents

"1" Quartz cluster principle http://www.cnblogs.com/zhenyuyaodidiao/p/4755649.html

"2" American Regiment Quartz Cluster Practice http://tech.meituan.com/mt-crm-quartz.html

"3" Quartz official website http://www.quartz-scheduler.org/documentation/

Introduction to the use of Quatz clustered timed tasks

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.