Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
This sample project download
first, Project creation
1, create a new project, import the corresponding package spring3.2.9+quqrtz2.2.1+commons-logging
It is simple to integrate, without any understanding of threads, and the spring manual is clearly explained. Just write a pojo, the rest is configured, and if you use Crontriggerbean, you can configure very complex task scheduling.
Write a common Java class
According to the business, writing a simple Java class is no different from a normal class. And configured on the spring configuration file. Cases:
Package Com.mucfc;import java.text.simpledateformat;import java.util.date;/** * Event class * Author Lin Bingwen ([email protected] Blog: Http://blog.csdn.net/evankaka) * Time 2015.4.29*/public class MyJob {public void run () {System.out.println (" Hello Spring with Quzrtz "+new simpledateformat (" Yyyy-mm-dd HH:mm:ss "). Format (new Date ()));}}
second, spring in the configuration
1. Create a job's bean instance
<!--config Job bean--<bean id= "MyJob" class= "Com.mucfc.MyJob"/>
2. Set upa task using METHODINVOKINGJOBDETAILF Actorybean
You only need to configure it, and the configuration information example is as follows:
<!--configuration Jobdetail--<bean id= "Myjobdetail" class= " Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean "> <!--used Job instance -- <property name= "TargetObject" > <ref bean= "MyJob"/> </property> <!--the method in the job instance-- > <property name= "Targetmethod" > <value>run</value> </property> </bean >
Description
TargetObject |
The target object, the Pojo that needs to be executed periodically |
Targetmethod |
Target method, that is, a Pojo method that needs to be executed periodically |
Concurrent |
By default, Quartz jobs is stateless and can lead to the interaction between jobs, if you specify two trigger for the same jobdetail, it is likely that the second job will begin before the first job is completed. If Jobdetail implements the stateful interface, this will not happen. The second job will not start until the first job is completed. To make jobs not run concurrently, set the concurrent flag to False |
3, the use of Crontriggerbean to establish rules, scheduling tasks
<!--configuring triggers trigger--><bean id= "Mytrigger" class= " Org.springframework.scheduling.quartz.CronTriggerFactoryBean "> <property name=" name "value=" Work_ Default_name "/> <property name=" group "value=" Work_default "/> <property name=" Jobdetail "> <ref bean= "Myjobdetail"/> </property> <property name= "cronexpression" > <!- -Run once every 5 seconds- <VALUE>0/5 * * * *?</value> </property></bean>
Description
Jobdetail |
Task details, which are the tasks that need to be dispatched |
Cronexpression |
Call the rule, that is, when it is called. See appendix 1 for detailed instructions. |
4. Use Schedulerfactorybean Packaging tasks
<!--configuration Scheduler factory--><bean id= "Scheduler" class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean "> <property name=" triggers "> < list> <ref bean= "Mytrigger"/> </list> </property></bean>
Description
Triggers |
triggers, which tasks are called |
Autostartup |
Whether the bean is automatically started and whether the timer task is started automatically after it is initialized. Set whether to automatically start the scheduler after initialization. |
Schedulername |
Set a name for the plan. Set the name of the Scheduler to fetch from the schedulerfactory . |
The entire configuration file is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd "> <!--config job bean--<bean id=" MyJob "class=" Com.mucfc.MyJob "/> <!--configuration Jobdeta Il--<bean id= "Myjobdetail" class= " Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean "> <!--Job Instance--<property Name= "TargetObject" > <ref bean= "myJob"/> </property> <!--Job instance Method--<property name= "Targe TMethod "> <value>run</value> </property> </bean> <!--configuring triggers trigger--><bean id=" Mytrigger "class=" Org.springframework.scheduling.quartz.CronTriggerFactoryBean "> <property name=" name "value = "Work_default_name"/> <propertY name= "group" value= "Work_default"/> <property name= "Jobdetail" > <ref bean= "myjobdetail"/> </prope rty> <property name= "Cronexpression" > <!--run every 5 seconds--<VALUE>0/5 * * * *?</value> </ Property></bean> <!--configuration Scheduler factory--><bean id= "Scheduler" class= " Org.springframework.scheduling.quartz.SchedulerFactoryBean "> <property name=" triggers "> <list> <ref bean= "Mytrigger"/> </list> </property></bean> </beans>
third, the use
Package Com.mucfc;import Org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class MyTest {public static void main ( String[] args) {ApplicationContext context=new classpathxmlapplicationcontext ("Beans.xml");}}
We know in spring that ApplicationContext will automatically generate an instance of the bean when it is loaded, which means the runtime timer will start executing and the result is as follows:
If you don't want it to start as soon as it loads, you can use Beanfactory to load the XML file and then open it manually
Package Com.mucfc;import Org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.springframework.beans.factory.beanfactory;import org.springframework.beans.factory.xml.XmlBeanFactory; Import Org.springframework.core.io.classpathresource;import Org.springframework.core.io.resource;public class MyTest {public static void main (string[] args) {//applicationcontext context=new classpathxmlapplicationcontext (" Beans.xml "); Resource res = new Classpathresource ("Beans.xml"); beanfactory bf = new Xmlbeanfactory (res); Scheduler scheduler= (Scheduler) Bf.getbean ("Scheduler"); try {Scheduler.start ();} catch (Schedulerexception e) { E.printstacktrace ();}}}
Core Concepts
1, Scheduler is a scheduler container, the container can be filled with a large number of jobdetail and trigger, when the container starts, the inside of each jobdetail will automatically according to the trigger step to execute.
2, Jobdetail is an executable work, which itself may be stateful.
3, trigger represents a scheduling parameter configuration, when to tune.
4, when Jobdetail and trigger in the Scheduler container registration, the formation of a good assembly of the work (Jobdetail and trigger a pair of children), can accompany the container start and dispatch execution.
5, Scheduler is a container, there is a thread pool in the container, used to schedule each job in parallel, which can improve the efficiency of the container.
iv. formatting of cron expressions
The format of the Quartz cron expression is very similar to that of the UNIX cron format, but there is still a little obvious difference. One of the differences is that the Quartz format supports scheduling down to the second level, while the UNIX cron program only supports up to minute levels. Many of our trigger plans are based on a second-level increment (for example, every 45 seconds), so this is a very good difference.
In UNIX Cron, the job (or command) to be executed is stored in a cron expression, at the sixth domain location. Quartz uses cron expressions to store execution plans. A crontrigger that references a cron expression is associated with the job at the scheduled time.
Another difference from the UNIX cron expression is the number of domains that are supported in an expression. UNIX gives five domains (minutes, hours, days, months, and weeks), and Quartz provides seven domains. Table 5.1 lists the seven domains supported by the Quartz cron expression.
Quartz Cron expressions support to seven domains
Name |
Whether you must |
Allowed values |
Special characters |
Seconds |
Is |
0-59 |
, - * / |
Score of |
Is |
0-59 |
, - * / |
When |
Is |
0-23 |
, - * / |
Day |
Is |
1-31 |
, - * ? /L W C |
Month |
Is |
1-12 or Jan-dec |
, - * / |
Week |
Is |
1-7 or Sun-sat |
, - * ? /L C # |
Years |
Whether |
Empty or 1970-2099 |
, - * / |
The names of the month and week are case insensitive. FRI and FRI are the same.
There are spaces between fields, which is the same as UNIX cron. It is indisputable that the simplest expression that we can write looks like this:
* * * ? * *
This expression fires a deployed job every second (every minute, every hour, every day).
• Understanding special characters
Like UNIX cron, Quartz cron expressions support the creation of more complex execution plans with special characters. However, Quartz is richer in support of special characters than standard UNIX cron expressions.
* Asterisk
Use an asterisk (*) to indicate that you want to include all valid values on this domain. For example, using an asterisk on a month field means that the trigger is triggered every month.
Examples of expression patterns:
0 * 17 * *?
Meaning: Trigger is fired every minute from 5 o'clock in the afternoon to 5:59 each day. It stops at 5:59 because the value 17 is on the hour field, and at 6 o'clock in the afternoon, the hour becomes 18, and the trigger is no longer heeded until the next day of 5 o'clock in the afternoon.
Use the * character when you want trigger to be fired on all valid values for that domain.
? Question mark
? Can only be used on day and week fields, but cannot be used concurrently on both domains. Can you think? The character is "I don't care what the value is on that field." "This differs from the asterisk, which indicates each value on the field." Is that you do not specify a value for the field.
The reason why a value cannot be specified at the same time on both domains is difficult to interpret or even incomprehensible. Basically, assuming that you specify a value at the same time, the meaning becomes ambiguous: consider if an expression has a value of 11 on the day field and WED is specified on the domain. So is it to trigger only in the 11th of each month, and exactly the day of Wednesday is excited? Or was it fired at number 11th in every Wednesday? The way to remove this ambiguity is that you cannot specify values on both domains at the same time.
Just remember that if you specify a value for one of the two fields, you have to put one on the other word value.
Examples of expression patterns:
0 10,44 14? 3 WEB
Meaning: Every Wednesday 2:10 and 2:44 in March is triggered.
, comma
A comma (,) is used to specify a list of values on a domain. For example, using the value 0,15,30,45 on the second field means that a trigger is triggered every 15 seconds.
Examples of expression patterns:
0 0,15,30,45 * * *?
Meaning: The trigger is triggered once per quarter.
/Slash
The slash (/) is used for the increment of the timesheet. We've just used a comma to indicate a 15-minute increment, but we can also write this 0/15.
Examples of expression patterns:
0/15 0/30 * * *?
Meaning: Trigger trigger every 15 seconds at the hour and the slightest.
-Medium Dash
A medium dash (-) is used to specify a range. For example, 3-8 on the hour field means "3,4,5,6,7 and 8 points." "The value of the domain does not allow a rollback, so a value like 50-10 is not allowed.
Examples of expression patterns:
0 45 3-8? * *
Meaning: 3 points in the morning to 8 points in the morning of 45 ticks trigger trigger.
L Letter
L describes the last value allowed on a domain. It is supported only by the day and week fields. When used on a day field, represents the last day of the month specified on the month field. For example, when JAN is specified on the current month field, L on the Japanese field will cause trigger to be triggered on January 31. If the monthly field is SEP, then L will indicate a trigger on September 30. In other words, the trigger is triggered on the last day of the corresponding month, regardless of the month specified.
Expression 0 0 8 L *? The meaning is to trigger trigger at 8:00 on the last day of each month. The * description on the month field is "every month".
When the L letter is used on the field, the last day of the week is indicated, that is, Saturday (or the number 7). So if you need 11:59 trigger trigger in the last Saturday of the month, can you use such expressions 0 59 23? L
When used on a week field, you can use a number to connect with L to represent the last one weeks of the month X. For example, an expression 0 0 12? * 2L is said to trigger trigger at the last one weeks of each month.
Do not allow range and list values to be associated with L
Although you can use the days of the week (1-7) with L, you are not allowed to use a range value and a list value with L. This can produce unpredictable results. |
W Letter
The W character represents weekdays (MON-FRI) and can only be used in the day domain. It is used to specify the most recent weekday from the specified day. Most of the business process is based on the work week, so the W character may be very important. For example, 15W in the daily field means "the most recent weekday of the month 15th." "If the number 15th is Saturday, then trigger will be triggered at 14th (Thursday), because the nearest 15th is Monday, this example will also be 17th (translator Unmi Note: Will not be triggered at 17th, if it is 15W, may be 14th number (15th is Saturday) or 15th ( Number 15th is Sunday) trigger, that is, can only appear in the adjacent day, if the day of the 15th is on weekdays directly on the day of execution. W can only be used in the specified day field as a single day and cannot be a range or list value.
# Number of Wells
The # character can only be used in the field of the week. It is used to specify which day of the week of the month. For example, if you specify the value of the week field as 6#3, it means the third Friday of the month (6= Friday, #3意味着月份中的第三周). Another example 2#1 meaning is the first Monday of the month (2= Monday, #1意味着月份中的第一周). Note that if you specify #5, but there is no 5th week in the month, then the month does not trigger.
Example:
Meaning of an expression
"0 0 12 * *?" trigger 12 o'clock noon every day.
"0 15 10?" * * "10:15 per day" trigger
"0 15 10 * *?" Daily 10:15 Trigger
"0 15 10 * * *" trigger 10:15 every day
"0 15 10 * * 2005" 2005-year daily 10:15 Trigger
"0 * 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:59 daily
"0 0/5 14 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily
"0 0/5 14,18 * *?" triggers every 5 minutes from 2 o'clock in the afternoon to 2:55 daily and from 6 o'clock in the afternoon to 6:55
"0 0-5 14 * *?" triggers every 1 minutes from 2 o'clock in the afternoon to 2:05 daily
"0 10,44 14?" 3WED "2:10 and 2:44 triggers in Wednesday of March every year
"0 15 10?" *mon-fri "Monday to Friday 10:15 trigger
"0 15 10 15 *?" 15th 10:15 per month
"0 L *?" 10:15 on the last day of the month
"0 15 10?" *6L "The last month of Friday 10:15 Trigger
"0 15 10?" * 6l2002-2005 "2002 to 2005 of the last of the monthly Friday 10:15 trigger
"0 15 10?" *6#3 "The third Friday 10:15 of the month is triggered
Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka
spring3.2.9+quqrtz2.2.1 Implementing timed instances