Quartz task scheduling framework and Spring integration

Source: Internet
Author: User

What is quartz?

Quartz is a feature-rich, open-source job scheduling library that can be integrated in virtually any Java application-from the smallest standalone application to the largest e-commerce system on the scale. Quartz can be used to create simple or complex schedule executions of dozens of, hundreds of, or even 100,000 jobs-jobs are defined as standard Java components that can execute almost anything that can be programmed to be executed. Quartz scheduling includes many enterprise-class features, such as JTA transactions and cluster support.

With the use of triggers combined with cron expressions , rich execution strategies can be implemented to meet production requirements.

MAVEN introduces Quartz package
<dependency>    <groupId>org.quartz-scheduler</groupId>    <artifactId>quartz</artifactId>    <version>2.2.1</version></dependency><dependency>    <groupId>org.quartz-scheduler</groupId>    <artifactId>quartz-jobs</artifactId>    <version>2.2.1</version></dependency>
Job

To better integrate with the spring framework, the following code chooses to inherit the class that implements the Job interface QuartzJobBean

import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.scheduling.quartz.QuartzJobBean;/** * * @author *** * email:***@163.com * @create 2018-04-20 10:33 AM **/public class HelloQuartzJob extends QuartzJobBean {    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {        System.out.println("Hello Quartz !!!!");    }}

executeInternalmethod to implement user-defined business logic internally.

Integration with spring

Job Configuration

    <bean id="helloQuartzJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">        <property name="jobClass" value="com.**.xtfx.quarz.**.job.HelloQuartzJob"/>        <!--任务名-->        <property name="name" value="helloQuartzJob"/>        <!--任务描述-->        <property name="description" value="任务描述"/>        <!--任务所属组-->        <property name="group" value="group"/>        <!--任务在没有触发器绑定时不消亡-->        <property name="durability" value="true"/>    </bean>

Trigger Configuration

    <bean id="helloQuartzJobCronTrigger"          class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">        <!--任务bean-->        <property name="jobDetail" ref="helloQuartzJob"/>        <!--任务触发条件-->        <property name="cronExpression" value="0 0/30 10-18 * * ?"/>    </bean>

Helloquartzjob Tasks Join Task Scheduler

    <!--任务总调度器-->    <bean id="stdScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">        <property name="transactionManager" ref="transactionManagerBusiness"/>        <property name="triggers">            <list>                <ref bean="helloQuartzJobCronTrigger"/>            </list>        </property>        <property name="jobDetails">            <list>                <ref bean="helloQuartzJob"/>            </list>        </property>    </bean>

Once the above configuration is included in the spring configuration, the task will be triggered every 30 minutes from 10:00 to 19:00 every day.

Quartz task execution mode and parameter passing

Task execution

After the job is fixed, it is executed concurrently in quartz. For multiple instances of the same job, they run independently, that is, when instance a of Helloquartzjob is not finished, and then the next trigger time for Helloquartzjob, another instance B, You will not be able to meet the current moment and only one instance of the task is running. Annotations DisallowConcurrentExecution can satisfy this requirement by guaranteeing that the class to which it is annotated will have only one instance running at any given time.

Parameter passing

For some cases where a job instance is required to pass in a parameter, the property passed in can be passed in JobDetailFactoryBean jobDataAsMap , and the job will be injected by the method of each property when instantiated, and set if the property and property methods are not set in the job class, the relevant parameters will need to be obtained in a way:

        //  获取运行参数        JobDataMap map = context.getJobDetail().getJobDataMap();

mapgets the corresponding variable from the parameter name.

If you want the next instance of the same job to get the parameters of the previous instance, you need to complete the following steps:

    • Class Top plus annotations@PersistJobDataAfterExecution
    • Writes the variables that need to be fetched by the next task and the corresponding property values before the previous task completes
     //  获取运行参数        JobDataMap map = context.getJobDetail().getJobDataMap();        ....        ....        map.put("times", map.getInt("times") + 1);
Integration

Based on the above content to modify the first section of the Helloquartzjob, yes its corresponding instance at any time only one in the execution, cut each time to output this is the number of times in the execution of the task.

Job file

import org.quartz.*;import org.springframework.scheduling.quartz.QuartzJobBean;/** * * @author *** * email:***@163.com * @create 2018-04-20 10:33 AM **/@PersistJobDataAfterExecution   //  数据保持@DisallowConcurrentExecution    //  多个任务不会同时执行public class HelloQuartzJob extends QuartzJobBean {    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {        //  获取运行参数        JobDataMap map = context.getJobDetail().getJobDataMap();        System.out.println("Hello Quartz 第 " + map.getInt("times") + " 执行 !!!");        map.put("times", map.getIntValue("times") + 1);    }}

Configuration file

    • Job
    <bean id="helloQuartzJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">        <property name="jobClass" value="com.**.xtfx.quarz.**.job.HelloQuartzJob"/>        <!--任务名-->        <property name="name" value="helloQuartzJob"/>        <!--任务描述-->        <property name="description" value="任务描述"/>        <!--任务所属组-->        <property name="group" value="group"/>        <!--任务在没有触发器绑定时不消亡-->        <property name="durability" value="true"/>                <!--输入属性值获取其他bean-->        <property name="jobDataAsMap">            <map>                <entry key="times" value="0"/>            </map>        </property>    </bean>
    • Trigger
    <bean id="helloQuartzJobCronTrigger"          class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">        <!--任务bean-->        <property name="jobDetail" ref="helloQuartzJob"/>        <!--任务触发条件-->        <property name="cronExpression" value="0 0/1 10-18 * * ?"/>    </bean>
    • Scheduler
    <!--任务总调度器-->    <bean id="stdScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">        <property name="transactionManager" ref="transactionManagerBusiness"/>        <property name="triggers">            <list>                <ref bean="helloQuartzJobCronTrigger"/>            </list>        </property>        <property name="jobDetails">            <list>                <ref bean="helloQuartzJob"/>            </list>        </property>    </bean>

Output results

开始触发quartz任务!!!!Hello Quartz 第 0 执行 !!!Hello Quartz 第 1 执行 !!!Hello Quartz 第 2 执行 !!!

Quartz task scheduling framework and Spring integration

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.