Spring Quartz cluster configuration

Source: Internet
Author: User

Quartz is an open-source job scheduling framework that is written entirely in Java and designed for use in J2SE and Java EE applications. It provides a great deal of flexibility without sacrificing simplicity. You can use it to create simple or complex schedules for executing a job.


In the project has a large number of background tasks need to schedule execution, such as building indexes, statistical reports, periodic synchronization data and so on, requires the task scheduling system with high availability, load balancing characteristics, the use of quartz will be very convenient.

The following is the integration of spring and quartz, while supporting cluster deployment. Quartz cluster support is the perception of task scheduling through a database.

1. Version used: Spring 3.1.2 + quartz 1.8.6

2. Database import quartz using the table, in the Quartz source compression package can find the corresponding SQL file, import.


3. Configure the database connection pool

Use the DataSource that are well-equipped in spring.

4. Configure Quartz.properties

# #Quartz The configuration file required by the Dispatch task # #org. The Quartz.scheduler.instanceName property can be any value that uniquely identifies an instance in a JDBC jobstore, but must be the same across all cluster nodes. Org.quartz.scheduler.instanceName = Instancescheduler # #org. Quartz.scheduler.instanceId property is auto, generating instances based on host name and timestamp Id. Org.quartz.scheduler.instanceId = AUTO Org.quartz.threadPool.class = Org.quartz.simpl.SimpleThreadPool org. Quartz.threadPool.threadCount = org.quartz.threadPool.threadPriority = 5 Org.quartz.threadPool.threadsInher Itcontextclassloaderofinitializingthread = True org.quartz.jobStore.misfireThreshold = 60000 # #org. Quartz.jobsto   The Re.class property is Jobstoretx, which persists the task to the data.   # #因为集群中节点依赖于数据库来传播 The state of the Scheduler instance, you can only apply the quartz cluster when using JDBC jobstore.   # #这意味着你必须使用 Jobstoretx or JOBSTORECMT as the Job store; you can't use Ramjobstore in a cluster. Org.quartz.jobStore.class = Org.quartz.impl.jdbcjobstore.JobStoreTX org.quartz.jobstore.driverdelegateclass= org.q Uartz.impl.jdbcjobstore.StdJDBCDelegate Org.quartz.jobStore.tablePrefix = Qrtz_ Org.quartz.jobSTore.maxmisfirestohandleatatime= # #org. The Quartz.jobStore.isClustered property is true, and you tell the Scheduler instance to participate in a cluster.    # #这一属性会贯穿于调度框架的始终, used to modify the default behavior of operations in a clustered environment. Org.quartz.jobStore.isClustered = true # #org. The Quartz.jobStore.clusterCheckinInterval property defines how often the scheduler instance is checked into the database (in units:   milliseconds).   # #Scheduler Check if other instances are not checked in when they should be checked in; This can indicate a failed Scheduler instance, and the current Scheduler will take over any Job that fails and is recoverable. # #通过检入操作, Scheduler also updates its own status record. The smaller the clusterchedkininterval, the more frequently the Scheduler node checks for Scheduler instances that fail.   The default value is 15000 (that is, 15 seconds). Org.quartz.jobStore.clusterCheckinInterval = 20000
5. Configure Timertask.xml

<?xml version= "1.0" encoding= "UTF-8"?> <!--field names (items) must be of value range special characters seconds is 0-59,-*/min is 0-59,-*/Time is 0-23,-*/the day of the month is 1-31,-*? /L W Month is 1-12 or JAN-DEC,-*/day of the week is 1-7 or SUN-SAT,-*? /L # Years no empty, 1970-2099,-*/--><! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" ><beans > <bean id= "secondprocessor" class= "Com.xxx.framework.back.SecondProcessor"/> <bean id= "minuteprocessor "class=" Com.xxx.framework.back.MinuteProcessor "/> <bean id=" Minutesjobdetail "class=" Org.springframework.scheduling.quartz.JobDetailBean "> <property name=" jobclass "value=" com.xx                  X.framework.timertask.minutequartzjob "/> <property name=" Jobdataasmap "> <map> <entry key= "Taskexecuters" > <list> <value>mi nuteprocessor</value> </list> </entry> <entry key= "Isworking" Value= "true"/><!--whether to turn on minute tasks-</map> </property> </bean > < Bean id= "Secondsjobdetail" class= "Org.springframework.scheduling.quartz.JobDetailBean" > <property name= "Jo Bclass "value=" Com.xxx.framework.timerTask.SecondQuartzJob "/> <property name=" Jobdataasmap "&G              T                           <map> <entry key= "Taskexecuters" > <list> <!--<value>secondProcessor</value>-</list> </en          try> <entry key= "isworking" value= "true"/><!--turn on the second level task-</map> </property> </bean > <bean id= "Minutestaskscheduler" class= "Org.springframework.scheduling.quar Tz. CrontRiggerbean "> <property name=" jobdetail "ref=" Minutesjobdetail "/> <property name=" CronExpre Ssion "value=" ${background.minuteexecute} "/> </bean > <bean id=" Secondstaskscheduler "class=" org.spring          Framework.scheduling.quartz.CronTriggerBean "> <property name=" jobdetail "ref=" Secondsjobdetail "/> <property name= "cronexpression" value= "${background.secondexecute}"/> </bean > <bean id= "timeTa          SK "class=" Org.springframework.scheduling.quartz.SchedulerFactoryBean "destroy-method=" destroy ">          <property name= "DataSource" > <ref bean= "source"/> <!--data source reference, contains all the tables required by the cluster-- </property> <property name= "TransactionManager" ref= "TransactionManager"/> <property N Ame= "Overwriteexistingjobs" value= "true"/> <property name= "Autostartup" value= "true"/> <pr Operty name= "ApplicationContextschedulercontextkey "value=" ApplicationContext "/> <property name=" configlocation "value=" classpath: Quartz.properties "/> <!--configlocation: location to indicate the configuration file for quartz--<property name=" triggers "&G              T <list> <ref bean= "Secondstaskscheduler"/><!---second task call--<ref Bean = "Minutestaskscheduler"/><!--minute task call-</list> </property> </bean ;</beans>
Relevant timertask.properties file

BACKGROUND.SECONDEXECUTE=0/1 * * * * * background.minuteexecute=0 0/1 * * * * background.hourexecute=0 0 0/1 * * background . daystartexecute=59 * *? background.dayexecute=23 4 * *? background.weekstartexecute=0 0 0? * MON

6. Writing the relevant classes

1) Writing Interface Ibatchprocessor

Public interface Ibatchprocessor {    void execute (int times);}


2) Implement class Minuteprocessor

public class Minuteprocessor implements ibatchprocessor{    @Override public    void execute (int times) {         System . Out.println ("Minuteprocessor times:" + times);}    }

3) Configure the job task two ways: Inherit Quartzjobbean class, rewrite executeinternal () ; Specify classes and methods with Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean.

The first way:

public class Minutequartzjob extends Quartzjobbean {private Logger Logger = Logger.getlogger (GetClass ());    Private list<string> taskexecuters;    /** * Minute counter */private static int minutercounter = 1;    private static Long lastminutertasktime =-1;    Private Boolean isworking;    Private Lock Minutelock = new Reentrantlock ();    Public list<string> Gettaskexecuters () {return taskexecuters;    } public void Settaskexecuters (list<string> taskexecuters) {this.taskexecuters = taskexecuters; } protected void Executeinternal (Jobexecutioncontext jobctx) throws Jobexecutionexception {if (!          isworking) return; if (Minutelock. Trylock ()) {try {schedulercontext schedctx = Jobctx.getscheduler (). Getconte                 XT ();                  ApplicationContext appctx = (applicationcontext) schedctx. Get ("ApplicationContext"); Long CUrrtime = System.currenttimemillis (); if (lastminutertasktime! =-1) {//interval of less than 55 seconds triggers a new minute-level task without executing if (currtime-l                           Astminutertasktime < 55000) {Logger.warn ("Problem with minute task trigger time");                      Return                  }} lastminutertasktime = Currtime;                               for (String taskitem:taskexecuters) {ibatchprocessor proc = (ibatchprocessor) appctx                      . Getbean (TaskItem);                 Proc.execute (Minutercounter);             } minutercounter++;             } catch (Exception ex) {ex.printstacktrace ();             } finally {Minutelock.unlock (); }} else {Logger.warn ("Unable to get a minute level background task lock!!!!!!         " );    }} public Boolean getisworking () {return isworking; } public void setisworking (bOolean isworking) {this.isworking = isworking; }}

The second way:


Direct use will report java.io.NotSerializableException exceptions. It's disgusting! Haha, this way to do it yourself to find a solution (rewrite Methodinvokingjobdetailfactorybean).


Spring Quartz cluster configuration

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.