Invoke the bean in the spring container and the dynamic dispatch task in the Quartz task

Source: Internet
Author: User
Quartz is an open source task scheduling framework, which provides a powerful task scheduling mechanism, while maintaining the simplicity of use. Quartz allows developers the flexibility to define scheduling schedules for triggers and to associate mappings of triggers and tasks. In addition, Quartz provides a persistence mechanism for scheduling the operating environment, which can save and restore the scheduling site, even if the system fails to shut down, the Task scheduling field data will not be lost. In addition, Quartz also provides a component-type listener, a variety of plug-ins, thread pool and other functions.

Spring provides a convenient Factorybean class for creating quartz scheduler, trigger, and jobdetail so that the benefits of injection can be enjoyed in the spring container. In addition, Spring provides some handy tool classes that directly package the beans in spring into legitimate tasks. Spring further reduces the difficulty of using quartz and can use quartz in a more spring-style manner. In summary, it provides support in two ways:
1) Provide a more bean-style extension class for the important component classes of quartz;
2) provides the Beanfactory class for creating scheduler, which facilitates the creation of corresponding component objects in the spring environment and the action of starting and stopping with the spring container life cycle.

First Step: Configure Schedulerfactorybean
Quartz's schedulerfactory is a standard factory class and is not suitable for use in spring environments. In addition, to ensure that the scheduler can perceive the life cycle of the spring container and complete the automatic start-up and shutdown operations, it is necessary to correlate the lifecycle of the scheduler with the spring container. So that after the spring container starts, Scheduler automatically starts to work, and the scheduler is turned off automatically before the spring container is closed. To do this, spring provides Schedulerfactorybean, a factorybean that roughly has the following features:
1) Provide configuration information for scheduler in a more bean-style manner;
2) The life cycle of scheduler and spring container is established, and the phase integration processes is related;
3) Replace Quartz's own configuration file with some or all of the property configuration.
The beans in the spring container can only be placed inside the schedulercontext into the job.



Java code    <bean name= "Scheduler"  class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean " >                    <!--  Inject data sources  -->              <property name= "DataSource" >                  <ref  Bean= "DataSource"  />             </ property>           <property name= " TransactionManager " ref=" Txmanager ">           </ property>                    <!--  Delay 30-second start scheduler -->      &Nbsp;      <property name= "Startupdelay"  value= "></" property>           <property name= " Schedulercontextasmap ">                  <map>             <!--  spring  managed service needs to be put here in order to inject success  -->                      <description>schedulercontextasmap</ description>                      <entry key= "Jobservice"  value-ref= "JobService"/>               </map>             </property>                    <!--  Configure the spring context with the Applicationcontextschedulercontextkey property  -->              <property name= " Applicationcontextschedulercontextkey ">                  <value>applicationContext</value>              </property>        </bean >  

Schedulerfactorybean Property Description:
The Triggers:triggers property is a trigger[] type, which allows you to register multiple trigger
calendars: type map, through which the calendar is registered to scheduler;
Jobdetails: Type jobdetail[], through which the scheduler is registered Jobdetail;
Autostartup:schedulerfactorybean If the scheduler is started immediately after initialization, the default is true. If set to False, you need to start scheduler manually;
Startupdelay: After Schedulerfactorybean initialization is complete, the delay in how many seconds to start scheduler, which defaults to 0, means to start immediately. If you do not immediately have the task you need to perform, you can use the Startupdelay property to start the scheduler delay for a short period of time so that spring can initialize the remaining beans in the container more quickly;

An important feature of Schedulerfactorybean is that it allows you to transfer information from the Quartz configuration file to the spring configuration file, with the benefit of centralized management of configuration information and the need to familiarize ourselves with the configuration file structure of multiple frameworks. Recalling a spring-integrated JPA, hibernate framework, you know that this is one of the tricks that spring often uses in integrating third-party frameworks. Schedulerfactorybean replaces the framework's own configuration file with the following properties:
DataSource: When you need to use a database to persist task scheduling data, you can configure the data source in quartz, or you can specify a spring-managed data source directly in spring through DataSource. If this property is specified, it will be overwritten by this datasource even if the data source is already defined in the quartz.properties.
TransactionManager: You can set a spring transaction manager through this property. When setting up DataSource, Spring strongly recommends that you use a transaction manager, otherwise the data table lock may not work properly;
Nontransactionaldatasource: In the case of a global transaction, if you do not want the scheduler execution data operation to participate in the global transaction, you can specify the data source through this property. In the case of spring local transactions, the use of the DataSource attribute is sufficient;
Quartzproperties: The type is properties, which allows you to define quartz attributes in spring. Its value overrides the settings in the Quartz.properties configuration file, which must be a legitimate property that quartz can recognize, and you can view the relevant documentation for quartz when you configure it.

After you have configured the data source DataSource, you need to insert the following data in the Quartz qrtz_locks table:
INSERT into qrtz_locks values (' trigger_access ');
INSERT into qrtz_locks values (' job_access ');
Otherwise it will be reported
Org.springframework.beans.factory.BeanCreationException:Error creating Bean with the name ' Scheduler ' defined in file [... \ Webapps\web-inf\classes\config\applicationcontext-quartz.xml]: Invocation of Init method failed; Nested exception is org.quartz.SchedulerConfigException:Failure occured during job recovery. [See nested exception:org.quartz.impl.jdbcjobstore.LockException:Failure obtaining DB row Lock:no row exists in table Q Rtz_locks for lock named:trigger_access [see nested Exception:java.sql.SQLException:No row exists in table Qrtz_locks F or lock named:trigger_access]] exception


The second step is to add the job dynamically

               Java Code    Jobdetail jobdetail = new jobdetail ("JobName",  "Jobgroup",                testjob.class);        jobdetail.setdescription ("Description");       crontrigger trigger  = new crontrigger ("Triggername",                 "Triggergroup",  "croncontent");       try {                if  (! Scheduler.isstarted ())  {                scheduler.start ();           }            scheduleR.schedulejob (Jobdetail, trigger);                   catch  (schedulerexception e)  {                   }  

The third step implements the job implementation class
Java Code    public class testjob extends quartzjobbean {            @Override        protected void  Executeinternal (Jobexecutioncontext context)  throws JobExecutionException {           Scheduler scheduler =  (Scheduler)   Context.getscheduler ();             String  Jobname = context.getjobdetail (). GetName ();            string jobgroup = context.getjobdetail (). Getgroup ();            //Get service objects in Jobexecutioncontext               try {                            //Get service objects in Jobexecutioncontext                

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.