Spring consolidates quartz for timed tasks

Source: Internet
Author: User

Recently in the project to use the scheduled task, but also take this opportunity to understand some common timing tasks, because the project uses the spring framework, so I will combine the spring framework to introduce.

A Classification
    • From the implementation of the technology to classify, there are currently three kinds of technology (or three products)
    1. Java comes with the Java.util.Timer class, which allows you to dispatch a Java.util.TimerTask task. Using this method allows your program to execute at a certain frequency, but not at a specified time. Generally used less, this article will not do a detailed introduction.
    2. Using quartz, this is a powerful scheduler that allows your program to execute at a specified time, and can be executed at a certain frequency, which is slightly more complex to configure, and will be described in more detail later.
    3. SPRING3.0 's own task, which can be thought of as a lightweight quartz and much simpler to use than quartz, will not be described in detail in this article.
    • From the inheritance of the job class, you can be divided into two categories:
    1. Job classes need to inherit from a particular job class base class. The need to inherit from the Org.springframework.scheduling.quartz.quartzjobbean;java.util.timer in quartz is required to inherit from Java.util.TimerTask.
    2. The job class is a normal Java class and does not need to inherit from any base class.

Note: A second approach is recommended, because all classes are generic and do not need to be treated differently beforehand.

    • from the trigger time of task scheduling, here is mainly for the job use of the trigger, mainly the following two kinds:
    1. Fires once every specified time, and the corresponding trigger in quartz is: Org.springframework.scheduling.quartz.SimpleTriggerBean
    2. Each time it is specified, it is triggered once, and the corresponding scheduler in Quartz is: Org.springframework.scheduling.quartz.CronTriggerBean

Note: These two triggers are not available for each task, such as the Java.util.TimerTask task, which can only be used for the first type. Both quartz and spring tasks can support both of these triggering conditions.

Two Usage Notes

This article will describe in detail how the quartz scheduled tasks are used.

First, the job class inherits from a specific base class: Org.springframework.scheduling.quartz.QuartzJobBean.

First step: writing task Classes

 PackageCom.ncs.hj;ImportOrg.quartz.JobExecutionContext;Importorg.quartz.JobExecutionException;ImportOrg.springframework.scheduling.quartz.QuartzJobBean; Public classSpringqtzextendsquartzjobbean{Private Static intCounter = 0; protected voidExecuteinternal (Jobexecutioncontext context)throwsjobexecutionexception {System.out.println (); Longms =System.currenttimemillis (); System.out.println ("\t\t" +NewDate (ms));        System.out.println (MS); System.out.println ("(" + counter++ + ")"); String s= (String) context.getmergedjobdatamap (). Get ("service");        System.out.println (s);    System.out.println (); }}
View CodeSecond, the job class does not inherit from a particular base class.

Spring can support this approach thanks to two classes:

Org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

These two classes correspond to the two ways in which spring supports the task scheduling, that is, the timer task mode and the Quartz method that the Java comes from earlier in this article. Here I only write Methodinvokingjobdetailfactorybean usage, the advantage of using this class is that our task class no longer needs to inherit from any class, but the normal pojo.

First step: Writing task classes

 PackageCom.ncs.hj;ImportOrg.quartz.JobExecutionContext;Importorg.quartz.JobExecutionException;ImportOrg.springframework.scheduling.quartz.QuartzJobBean;Importjava.util.Date; Public classSpringqtz {Private Static intCounter = 0; protected voidExecute () {Longms =System.currenttimemillis (); System.out.println ("\t\t" +NewDate (ms)); System.out.println ("(" + counter++ + ")"); }}
View Code

Step two: Spring's configuration file

    <!------------Configure the Scheduler quartz, where Jobdetail is configured in two ways------------ -          <!--mode one: Using Jobdetailbean, the task class must implement the job interface -           <BeanID= "Myjob"class= "Org.springframework.scheduling.quartz.JobDetailBean">           < Propertyname= "Name"value= "Examplejob"></ Property>           < Propertyname= "Jobclass"value= "Com.ncs.hj.SpringQtz"></ Property>          < Propertyname= "Jobdataasmap">                <Map>                    <entryKey= "Service"><value>Simple is the Beat</value></entry>                </Map>    </ Property>        </Bean>         <!--Please comment out the mode one at run time!  -          <!--mode two: Using Methodinvokingjobdetailfactorybean, the task class can not implement the job interface, through the Targetmethod to specify the calling method -          <!--define methods in the target bean and bean -        <BeanID= "Springqtzjob"class= "Com.ncs.hj.SpringQtz"/>        <BeanID= "Springqtzjobmethod"class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">        < Propertyname= "TargetObject">            <refBean= "Springqtzjob"/>        </ Property>        < Propertyname= "Targetmethod">  <!--the name of the method to execute -            <value>Execute</value>        </ Property>    </Bean>    <!--======================== scheduling Trigger ======================== -    <BeanID= "Crontriggerbean"class= "Org.springframework.scheduling.quartz.CronTriggerBean">        < Propertyname= "Jobdetail"ref= "Springqtzjobmethod"></ Property>        < Propertyname= "Cronexpression"value= "0/5 * * * *?"></ Property>    </Bean>    <!--======================== Dispatch Factory ======================== -    <BeanID= "Springjobschedulerfactorybean"class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean">        < Propertyname= "Triggers">            <List>                <refBean= "Crontriggerbean"/>            </List>        </ Property>    </Bean>  
View Code

To this, spring in Quartz basic configuration is finished, of course, before using, to import the corresponding spring package and quartz package, these will not be said.

About the cronexpression expression, here's a little bit of explanation:

Special characters allowed for field allowed values
Seconds 0-59,-*/
Sub 0-59,-*/
Hours 0-23,-*/
Date 1-31,-*? /L W C
Month 1-12 or JAN-DEC,-*/
Week 1-7 or Sun-sat,-*? /L C #
Year (optional) leave blank, 1970-2099,-*/


expression meaning  
"0 0 12 * *" Trigger   12 o'clock noon;
"0 15 10? * * "trigger   daily 10:15;
" 0 15 10 * * "10:15   per day;
" 0 15 10 * *? * "Trigger   daily 10:15;
" 0 15 10 * *? 2005 "2005 Years a day 10:15 trigger  
0 * 14 * *?" Every 1 minutes from 2 o'clock in the afternoon to 2:59 daily triggers  
"0 0/5 14 * *?" every 5 minutes during the Daily 2 o'clock in the afternoon to 2:55 Trigger & nbsp
"0 0/5 14,18 * *?" triggers the   every 5 minutes from 2 o'clock in the afternoon to 2:55 and 6 o'clock in the afternoon to 6:55;
"0 0-5 14 * *?" triggers the   every 1 minutes during daily 2 o'clock in the afternoon to 2:05;
0 10 , 44 14? 3 WED "March Wednesday 2:10 and 2:44 trigger  
" 0 15 10? * Mon-fri "from Monday to Friday 10:15 trigger  
" 0 15 10 15 *? "15th 10:15 per month, trigger  
" 0 L *? "The last day of the month 10:15 triggers the  
" 0 15 10? * 6L "last Friday 10:15 to trigger  
" 0 15 10? * 6L 2002-2005 "2002 to 2005 the last of the monthly Friday 10:15 trigger  
" 0 15 10? * 6#3 "The third Friday 10:15 of the month triggers  
6 o '   per morning;
0 6 * * *&NBSP;
every two hours  
0 */2 * * *&NBSP;
Every two hours from 11 o'clock to 8 in the morning, and eight   in the morning;
0 23-7/2,8 * * *&NBSP;
4th for each month and Monday to Friday at three  
11 0 * 1-3&NBSP;
January 1 morning 4  
0 4 1 1 * 

Reference: http://gong1208.iteye.com/blog/1773177

http://kevin19900306.iteye.com/blog/1397744

Spring consolidates quartz for timed tasks

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.