Use Quartz in Spring

Spring for the creation of the Quartz Scheduler, Trigger and JobDetail provides a convenient FactoryBean class to be able to enjoy the benefits of injection in the Spring container. In addition, Spring also provides convenient tools for direct packaging in Spring Bean as a legitimate task. Spring further reduces the difficulty of using Quartz, able to more stylized way to use Quartz. In summary, Spring provides support for both.

(1) provides a more extended Bean-style class Quartz important component class.

(2) providing the Scheduler creates BeanFactory class, facilitate the creation of an object in a corresponding component Spring environment, and performs lifecycle Spring container for starting and stopping operation.

1. Create JobDetail

Users can directly use a configuration of Quartz JobDetail JobDetail Bean in the Spring, but with reference to use JobDetail constructor, present the inconvenience of use accustomed Spring configured by the user attribute. To this end, Spring provides a more Bean-style JobDetailFactoryBean by extending JobDetail.

In addition, Spring also provides a MethodInvokingJobDetailFactoryBean, the method can be packaged into a Spring container Bean Quartz tasks this FactoryBean, so developers do not have to create the corresponding class for Job.

1)JobDetailFactoryBean

JobDetailFactoryBean extended to the Quartz JobDetail. When using the Bean statement JobDetail, Bean name to the name of the task, if your group is not specified, the default group. In addition JobDetail attributes further defines the following properties.

(1) jobClass: type Class, Job task to achieve class interface.

(2) beanName: the id of the default Bean, Bean explicitly specified by the name attribute, which corresponds to the name of the task.

(3) jobDataAsMap: type Map, the task to provide a value corresponding JobDataMap. The need to provide this property, because the user is unable to provide information to JobDataMap type of property in the Spring configuration file, so the value of Spring JobDataMap by jobDataAsMap settings.

(4) applicationContextJobDataKey: SpringApplicationContext user can be saved to the JobDataMap reference to access ApplicationContext Job's code. To achieve this object, the user needs to specify a key for storing in the ApplicationContext jobDataAsMap. If you do not set this key, JobDetailBean ApplicationContext will not put the JobDataMap.

(5) jobListenerNames: type String [], specify the name in JobListeners Scheduler is registered, so that these event listeners to this task of monitoring.

The following configuration fragments using a JobDetail JobDetailBean arranged in Spring.

<bean name="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean"
  p:jobClass="com.smart.quartz.MyJob"
  p:applicationContextJobDataKey="applicationContext">
  <property name="jobDataAsMap">
    <map>
      <entry key="size" value="10" />
    </map>
  </property>
</bean>

JobDetaiIFactoryBean encapsulates MyJob task class, and for the Job JobDataMap provided corresponding to size data of a key. In addition, by specifying applicationContextJobDataKey, let Job's JobDataMap hold a reference SpringApplicationContext of.

In this way, MyJob at runtime to access the size and ApplicationContext by JobDataMap. MyJob look at the code, as shown in the following code.

public class MyJob implements StatefulJob {
    public void execute(JobExecutionContext jctx) throws JobExecutionException {
        Map dataMap = jctx.getJobDetail().getJobDataMap();//①获取JobDetail关联的JobDataMap
        //Map dataMap = jctx.getTrigger().getJobDataMap();
        String size =(String)dataMap.get("size");//
        ApplicationContext ctx = (ApplicationContext)dataMap.get("applicationContext");//
        System.out.println("size:"+size);
        dataMap.put("size",size+"0");//④ JobDataMap whether changes will be made to depend on the type of task persistence 
        
        String COUNT = (String) dataMap.get ( "COUNT" ); 
        System.out.println ( "COUNT:" + COUNT); 
    } 
}

Get size values ​​at ②, ③ at the key applicanonContext can get ApplicationContext, with reference to ApplicationContext, Job will be no obstacles to access any Bean Spring container. JobDataMap MyJob can make changes to the execute () method, as shown at ④. If MyJob implement the Job interface, then this change for the next execution is not visible; if MyJob realized StatefulJob interface, this change to the next execution is visible.

2)MethodInvokingJobDetailFactoryBean

Typically, tasks are defined in a service class method. In this case, in order to satisfy a predetermined QuartzJob interface, also you need to define a reference traffic class method implementation class. To avoid creating a line that contains only the calling code implementation class Job, Spring provides MethodInvokingJobDetailFactoryBean, by means of the FactoryBean, a method may be packaged Bean to satisfy the requirements of the Quartz Job. As a concrete example:

< Bean the above mentioned id = "jobDetail_1" 
  class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" 
  the p-: targetObject-ref = "myService"   // a reference ① Bean
  the p-: targetMethod
= "doJob" // ② target Bean method
  P: Concurrent
= "to false" /> whether // ③ specified task state in the final package < the bean ID = "myService" class = "com.smart.service.MyService" />

The jobDetail1_1 MyService # doJob () encapsulated into a task, and by the type attribute specifies the concurrent tasks. By default encapsulation stateless task. If you want to have a package for the state of the task, only the concurrent property to false on it. Spring type attribute specified by concurrent task name can be described in a more direct way of task execution (stateful task can not be performed concurrently, stateless tasks can be executed concurrently), the internal mechanisms are not familiar Quartz users, compared stateful, concurrent apparently lied some more concise.

Myservice service class has a doJob () method, which code is as follows:

public  class the MyService {
    public  void doJob () { // ① target method is packaged into tasks 
       System.out.println ( "in MyService.dojob ()." ); 
   } 
}

doJob () method may be either static, or may be non-static, but can not have the reference method. JobDetail generated by MethodInvokingJobDetailFactoryBean not be serialized, it can not be persisted to the database. If you wish to use persistent task, the user can only create a formal Quartz Job implementation class.

 

2. Create Trigger

Quartz Another important component is the Trigger, Spring, respectively, in a similar way of thinking provides a more Bean-style SimpleTriggerFactoryBean and CronTriggerFactoryBean extension classes for SimpleTrigger and CronTrigger, these two classes can more easily extend to the way in Spring Bean configure Trigger.

1)SimpleTriggerFactoryBean

By default, Trigger name configured by SimpleTriggerFactoryBean Bean is the name, which belongs to the default group. SimpleTriggerFactoryBean SimpleTrigger on the basis of the following new properties.

(1) jobDetail: corresponding JobDetail.

(2) beanName: the id of the default Bean, Bean explicitly specified by the name attribute, which corresponds to the name of the Trigger.

(3) jobDataAsMap: JobDataMap value provided for the Trigger Type Map associated.

(4) startDelay: How much time delay start trigger, in milliseconds, default value is 0.

(5) triggerListenerNames: type String [], specify the name in TriggerListener Scheduler is registered, so that these listeners of the trigger event monitoring.

The following example uses SimpleTriggerFactoryBean define a Trigger, the Trigger and associated jobDetail, after 1 second delay start time interval of 2 seconds repeatedly performed 100 times. In addition, also provided JobDataMap data Trigger.

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"
  p:jobDetail-ref="jobDetail" 
  p:startDelay
="1000"
  p:repeatInterval
="2000"   p:repeatCount="100">   <property name="jobDataAsMap"> //①     <map>       <entry key="count" value="10" />     </map>   </property> </bean>

Special attention is required, Map data arranged in ① to the filling of the JobDataMap Trigger, the value must be obtained in the following manner when the configuration tasks:

public  class MyJob the implements StatefulJob {
     public  void Execute (the JobExecutionContext jctx) throws JobExecutionException { 
        the Map Datamap = jctx.getTrigger () getJobDataMap ();. // ① Trigger acquisition of the JobDataMap 
        
        String COUNT = (String) dataMap.get ( "COUNT" ) ; 
        dataMap.put ( "COUNT", "30"); // ② JobDataMap changes will not be persistent, does not affect the execution of the next 
    } 
}

2)CronTriggerFactoryBean

CronTriggerFactoryBean expansion in CronTrigger, name of the trigger is the name of the Bean, saved in the default group. On the basis of CronTrigger, new attributes and SimpleTriggerFactoryBean substantially the same, and also the method of configuration similar SimpleTriggerFactoryBean. A simple example is given below:

<bean id="checkImagesTrigger" 
  class="org.springframework.scheduling.quartz.CronTriggerBean"
  p:jobDetail-ref="jobDetail"
  p:cronExpression="0/5 * * * * ?"/>

 

3. Create Scheduler

Quartz is the standard SchedulerFactory factory class, is not suitable for use in a Spring environment. In addition, in order to ensure Scheduler can sense the life cycle of the Spring container, after the Spring container starts, Scheduler automatically start working, but before the Spring container is closed, shut down automatically Scheduler. To this end, Spring provides SchedulerFactoryBean, this FactoryBean generally have the following features.

(1) Bean style in a more way to provide configuration information for the Scheduler.

(2) Let Scheduler and life cycle of the Spring container associate Aioi information.

(3) in place by means of configuration attributes Quartz own profile.

SchedulerFactoryBean configuration example of a view, as shown in the following code.

<bean id="scheduler"
  class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  <property name="triggers"> //①注册多个Trigger
    <list>
      <ref bean="simpleTrigger" />
    </list>
  </property>
  <property name="schedulerContextAsMap">  //②以Map类型设置SchedulerContext数据
    <map>
      <entry key="timeout" value="30" />
    </ Map > 
  </ Property > 
  < Property name = "the configLocation"  
        value = "CLASSPATH: COM / Smart / Quartz / the quartz.properties"  /> // ③ display configuration file address specified Quartz
 </ the bean >

The Trigger property triggers SchedulerFactoryBean [] type, can be registered by the plurality of Trigger property, registered at a Trigger in ①. Scheduler has a similar ServletContext of SchedulerContext. SchedulerFactoryBean allows the user to set parameter values ​​SchedulerContext, as shown at ② in the form of a Map. By default, Quartz query classpath quartz.properties profile, the user can also explicitly specify the location of the configuration file by configLocation attributes, as shown at ③.

Addition to the attributes used in the examples, SchedulerFactoryBean also has some common properties.

(1) calendars: type Map, registered to the Calendar Scheduler through the property.

(2) jobDetails: type JobDetail [], the register JobDetail Scheduler through the property.

(3) autoStartup: SchedulerFactoryBean start immediately after initialization whether Scheduler, the default is true. If set to false, you need to manually start the Scheduler.

(4) startupDelay: SchedulerFactoryBean after completion of initialization, the number of seconds delay start Scheduler, the default value is 0, indicating start immediately. Unless you have a job that requires immediate execution, under normal circumstances, you can let the property Scheduler delayed start after a short time, so that Spring can initiate remaining in the container Bean faster.

SchedulerFactoryBean an important function is to allow users to transfer information to a Spring configuration file Quartz profile, resulting benefits are centralized management of configuration information, and we do not have to be familiar with a variety of frame has the configuration file structure differences. Memories of a Spring Hibernate integration framework, to know that this is the usual tricks used in the Spring when integrating third-party frameworks. The following configuration file attribute instead of the frame itself.

(1) datasource: When it is desired to use the database persistent scheduling data, the user can configure the data source Quartz can specify a data source Spring managed directly by the datasource in Spring. If this attribute is specified, then even in the quartz.properties data source has been defined, it will be covered dataSource.

(2) transactionManager: may be provided by means of a Spring transaction manager the property. When you set datasource, Spring is strongly recommended to use a transaction manager, otherwise the data table locks may not work properly.

(3) nonTransactionalDataSource: in the case of a global transaction, if the user does not wish to perform an operation related data Scheduler to participate in a global transaction, the data source can be specified by this attribute. Spring in the case of local affairs, using datasource property is sufficient.

(4) quartzProperties: type Properties, allows the user to define the attributes in Spring Quartz, which overrides the setting value quartz.properties profile. These attributes must be able to recognize the legitimate property Quartz, at configuration time, need to see the documentation of Quartz.

Here is an example of a configuration quartz.properties properties:

<bean id="scheduler"
  class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
  ...
  <property name="quartzProperties">  //①Quartz属性项1
    <props>
      <prop key="org.quartz.threadPool.class">
        org.quartz.simpl.SimpleThreadPool
      </prop>
      <prop key="org.quartz.threadPool.threadCount">10</prop>//②Quartz属性项2
    </props>
  </property>
</bean>

In practice, we do not always deployed when the program will determine which tasks need, often need to dynamically generate triggers and tasks at runtime based on business data. Users can obtain the code calls SchedulerFactoryBean Scheduler instance, and then dynamic registration triggers and tasks at runtime through.

 

Guess you like

Origin www.cnblogs.com/jwen1994/p/11355356.html