Spring+quartz, dynamic registration job

Source: Internet
Author: User

There are many examples of the integration of Spring+quartz, not to mention integration here;


If the configuration of fixed job, often use Methodinvokingjobdetailfactorybean, but also good, but the root of the problem is that this class does not implement the serializable interface, resulting in the job information into the database, it does not work,

This is one of the triggers. The following is the main content of the article.


Previously mentioned target

1.job information stored in the database

2. Can add a fixed job to the project (written in the configuration file), you can also add dynamic job (such as scheduled to send messages, add the job by Java code)

3. To be able to use value in the actual project


Configuration step Start (plainly, writing a program is writing a configuration file)

1. Configure DataSource, Schedulerfactorybean

Using MySQL

    <!--datasource-->    <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >        <property name= "Driverclassname" value= "${jdbc.driverclassname}"/>        < Property name= "url" value= "${jdbc.url}"/>        <property name= "username" value= "${jdbc.username}"/>        <property name= "Password" value= "${jdbc.password}"/>    </bean>

    <!--schedulerfactory-->    <bean id= "Schedulerfactory" lazy-init= "true" class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean ">        <property name=" Autostartup "value=" ${ Scheduler.auto.startup} "/>        <property name=" DataSource "ref=" DataSource "/>        <property name=" Triggers ">            <list>                <ref bean=" Testfixedtriggerbean "/>            </list>        </property >    </bean>


${scheduler.auto.startup} is a Boolean variable that specifies whether to automatically enable

MySQL database SQL file see the project others directory, can also go to quartz website Download http://www.quartz-scheduler.org/


2. Configure a fixed job

Because of the need to serialize (Serializable) when the job information is stored in the database, the Methodinvokingjobdetailfactorybean object cannot be used.

We recommend using Crontriggerfactorybean, which is configured as follows

    <bean id= "<span style=" font-family:arial, Helvetica, Sans-serif; " >testfixedtriggerbean</span><span style= "font-family:arial, Helvetica, Sans-serif;" > "</span> class=" Org.springframework.scheduling.quartz.CronTriggerFactoryBean ">        <property Name= "Jobdetail" ref= "Testfixedjobdetailbean"/>        <property name= "cronexpression" value= "${ Test.fixed.cron.expression} "/>    </bean>
${test.fixed.cron.expression} is the corresponding cron expression, such as 0/5 * * * *?


Configure the corresponding Jobdetailfactorybean

    <bean id= "Testfixedjobdetailbean"          class= "Org.springframework.scheduling.quartz.JobDetailFactoryBean" >        <property name= "Jobclass" value= "Com.andaily.service.scheduler.TestFixedJobDetailBean"/>        < Property name= "Durability" value= "true"/>    </bean>

Note: Be sure to put durability=true; Jobclass is to perform the task of the specific class, need to be the subclass of the job, generally inherit Quartzjobbean can


public class Testfixedjobdetailbean extends Quartzjobbean {    @Override    protected void executeinternal ( Jobexecutioncontext context) throws Jobexecutionexception {        System.out.println ("I am working on" + New Date ());    }}


Overwrite Executeinternal method, write business implementation inside

Note: Because the code here does not have a transaction, if the business method requires a transaction, you have to handle it yourself.



3. Configure the dynamic job

The so-called dynamic, is in the program run, by the use of the person manually to join the job, commonly used such as mail timed sending, task reminders and so on

The essence is to tell the job to schedulerfactory and let it handle it.

For this we add the following objects

Dynamicschedulerfactory--Management of dynamic job registration, deletion, etc., need to be configured in the XML configuration file; Of course, a reference to the Schedulerfactory object must be required

Dynamicjob--Contains all the information required by the dynamic job, such as cron expression, etc. created by the program when needed

Public final class Dynamicschedulerfactory implements Initializingbean {private static final Logger LOG = Loggerfactor    Y.getlogger (Dynamicschedulerfactory.class);    private static Scheduler Scheduler; Public dynamicschedulerfactory () {}/** * Register a job * * @param job Dynamicjob * @return True I S Register successful * @throws Schedulerexception */public static Boolean registerjob (Dynamicjob job) throws        schedulerexception {final Triggerkey Triggerkey = Job.triggerkey ();            if (scheduler.checkexists (Triggerkey)) {final Trigger Trigger = Scheduler.gettrigger (Triggerkey);        throw new Schedulerexception ("already exist trigger [" + Trigger + "] by key [" + Triggerkey + "] in Scheduler");        } final Cronschedulebuilder Cronschedulebuilder = Cronschedulebuilder.cronschedule (Job.cronexpression ()); Final Crontrigger Crontrigger = Triggerbuilder.newtrigger (). withidentity (Triggerkey). WIThschedule (Cronschedulebuilder). build ();        Final Jobdetail jobdetail = Job.jobdetail ();        Final Date date = Scheduler.schedulejob (Jobdetail, Crontrigger);        Log.debug ("Register dynamicjob {} on [{}]", job, date);    return true;  }/** * Remove exists job * * @param existjob A dynamicjob which exists in Scheduler * @return True is Remove successful * @throws schedulerexception */public static Boolean removejob (Dynamicjob existjob) throws        schedulerexception {final Triggerkey Triggerkey = Existjob.triggerkey ();        Boolean result = false;        if (scheduler.checkexists (Triggerkey)) {result = Scheduler.unschedulejob (Triggerkey);        } log.debug ("Remove dynamicjob {} result [{}]", existjob, result);    return result;    } public void Setscheduler (Scheduler Scheduler) {dynamicschedulerfactory.scheduler = Scheduler; } @Override public void Afterpropertiesset () throwS Exception {assert.notnull (Scheduler, "Scheduler is null");    Log.info ("Initial dynamicschedulerfactory successful, scheduler instance: {}", scheduler); }

public class Dynamicjob {//job class private class<? extends job> target;    Cron expression private String cronexpression;    Private String jobgroup = Scheduler.default_group;    Must unique private String jobName;    private transient triggerkey triggerkey;    private transient jobdetail jobdetail;    Default public Dynamicjob () {} public dynamicjob (String jobName) {this.jobname = JobName; } public class<?    Extends job> target () {return target;        } public dynamicjob target (class<? extends job> target) {this.target = target;    return this;        } public dynamicjob cronexpression (String cronexpression) {this.cronexpression = cronexpression;    return this;    } public String Jobgroup () {return jobgroup;        } public dynamicjob Jobgroup (String jobgroup) {this.jobgroup = Jobgroup;    return this;    } public String JobName () {return jobName; } publiC dynamicjob JobName (String jobName) {this.jobname = JobName;    return this; Public Triggerkey Triggerkey () {if (Triggerkey = = null) {Triggerkey = Triggerkey.triggerkey (this).        JobName, This.jobgroup);    } return Triggerkey;                    } public Jobdetail Jobdetail () {if (Jobdetail = = null) {Jobdetail = Jobbuilder.newjob (target)        . withidentity (This.jobname, This.jobgroup). Build ();    } return jobdetail; }/* * Transfer data to Job * ' in job ' use * CONTEXT.GETMERGEDJOBDATAMAP (). Get (Key) * */Public Dynamicjob        Addjobdata (String key, Object value) {final Jobdetail detail = Jobdetail ();        Final Jobdatamap Jobdatamap = Detail.getjobdatamap ();        Jobdatamap.put (key, value);    return this;    } public String Cronexpression () {return this.cronexpression; }}


With these two basic classes, the job of implementing dynamic jobs is as follows

1). Create Dynamicjob instances (Jobname,cronexpression and target are required; target is an implementation of the job class)

2). Call Dynamicschedulerfactory registerjob to register a job or call Removejob to delete the added job


An example is as follows:

            Dynamicjob dynamicjob = Createdynamicjob ();            Dynamicjob.addjobdata ("Mailguid", Mail.guid ());//transfer parameter            try {                Dynamicschedulerfactory.registerjob (dynamicjob);            } catch (Schedulerexception e) {                throw new illegalstateexception (e);            }


Note: About target in Dynamicjob.

This field is a class type and requires implementation to be an implementation class for a job. It's not specific.



To this, to complete;


I've put the code for the example on Git, address: http://git.oschina.net/mkk/spring-dynamic-job We discuss and study together.






Spring+quartz, dynamic registration job

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.