Spring---java timer, spring timer, and quartz timer.

Source: Internet
Author: User
Tags stub
In real life, there are examples such as boiling water, generally burned for 20 minutes after the water, will need to change water, and then burn for 20 minutes, water opened again, continue to remind, such as work, every 8 o'clock in the morning alarm clock will be in time to remind, then in the Java program How to achieve this has been set the timing of the task? , the following describes the business requirements for how to implement timers to operate some timed tasks.
There are three main ways to implement timing in the current Java program: Java timer, spring timer, quartz timer. Let's talk about their applications in turn. Application of <1>java timer.              In fact, Java has a way to solve the timer task early, Java provides class Java.util.TimerTask class thread-based way to implement the task of timed tasks, and then provide Java.util.Timer class to register the call, first create a class   Ringtask   Inheritance   Java.util.TimerTask, implement the Run method, the relevant code is as follows:       Package timer; Import Java.util.TimerTask; /**  * This is a bell-ringing program that must be played once a time  * @author Sam  *  */public class Ringtask extends the public ring Task () {//Todo auto-generated constructor stub} public ringtask (int s,int d) {//Todo auto-generated constructor stub This.second = s; This.delay  = D; int second = 1; int delay  = 1; public void Setsecond (int second) {This.second = second.} public void Setdelay (int delay) {this.delay = delay;} @Overr IDE public void Run () {//TODO auto-generated Method stub System.out.println ("I am a ringing program!") + "The first time I rang the bell delayed" +delay+ "seconds. "); System.out.println ("Ring the bell!" every "+second+" second time); After    is defined, the following registration call is required, and the method for registering the call is as follows:       public static void main (string[] args) {//Call T in Java Timer mode Imer timer = new timer (); timer.scheduLe (New Ringtask (3,3),  //need to register the timing class 3000,            //First delay 3 seconds of time 3000);            //every 3 seconds.     A simple Java timer is written, convenient and brief, but with bad disadvantages: If you need to implement a scheduled daily 7 o'clock in the morning, and 7 o'clock in the morning do not need a reminder on weekends, this is not enough, and if you need the server to trigger the timer on the first turn, then this registration call method is not possible.
Application of <2>spring timer. The         Spring timer is a more mature way to apply in the spring framework, where spring refers to the configuration file in the invocation section of the scheduled task, making the timer trigger more flexible, and the spring timer is implemented, Still need to inherit   Java.util.TimerTask, implement the Run method, the example class has been given above, the configuration of the call is as follows:          <!--timer configuration (Spring timer --> <!--to schedule the bean configuration--> <bean id= "Ringtask" timer. Ringtask "> <!--Assign value to second 3--> <property name=" Second "> <value>3</value>     </property> <!--assign value to attribute delay 3--> <property name= "delay" > <value>3</value>   &NB Sp </property> </bean> <!--Configure a trigger to configure the parameters of a trigger--> <bean id= "Scheduleringtask" class= " Org.springframework.scheduling.timer.ScheduledTimerTask "> <property name=" delay "value=" 3000 "></" property>           <!--first time delay 3 seconds--> <property name= "period" value= "3000" >< /property>           <!--execute once every 3 seconds--> <property name= "TimerTask" ref= "Ringtask" & GT;</property>    <!--to develop triggered class--> </bean> <!--master schedule for starting timer--> <bean id= " Timerfactory "class=" Org.springframework.scheduling.timer.TimerFactoryBean "> <property name=" Scheduledtimertasks "> <list> <ref bean=" Scheduleringtask "/> </list> </property> </bean >     In the call is not flexible, and can implement the server has been started, the execution of the timer into the scope of the monitored, meet the conditions immediately trigger execution. However, there are still shortcomings: the specific date of the specified month and a minute to perform the task is still not resolved. ================================================== ==================================================
<3>quartz TimerQuartz is a more powerful timer based on the spring framework, which not only makes it easy to implement the previous two timer functions, but also implements a very complex set of time triggering tasks, quartz there are two ways to schedule timed tasks, one with spring Methodinvokingjobdetailfactorybean proxy class, quartz a function of the task class directly through the proxy class, and the second is the task class inheriting Quartzjobbean class    or implement Org.quartz.Job interface, quartz through the parent class or interface for scheduling.     First of all to see the implementation of the previous two timer functions, now first to give an example, such as boiling water, every 1 hours to boil once, for a timely reminder, and then change water, then burn, .... Specific water boiling timing class code as follows: Package timer; Import Org.quartz.Job; Import Org.quartz.JobExecutionContext; Import org.quartz.JobExecutionException; Import Org.springframework.scheduling.quartz.QuartzJobBean; /** * This is a hot water program, it is necessary to heat up after a period of time, only to remind the change of water * @author Sam * This class whether inheriting Quartzjobbean or implement Org.quartz.Job are all OK * * * public class Hotwat Ertask extends Quartzjobbean/*implements job*/{
public void execute (jobexecutioncontext arg0)//throws Jobexecutionexception {////TODO auto-generated method stub System.out.println ("I am a hot water program, I first boil to need 1 hours"); System.out.println ("Water is now boiling, to change the water in time!"); @Override protected void executeinternal (Jobexecutioncontext arg0) throws Jobexecutionexception {//TODO Auto-genera Ted Method Stub System.out.println ("I'm a hot water program, I need 1 hours for first boiling"); System.out.println ("Water is now boiling, to change the water in time!"); } }
class defined, the following needs to be configured, the configuration code is as follows:          <!--Configure task class--> <bean id= "Hotwatertask" class= "or G.springframework.scheduling.quartz.jobdetailbean "> <property name=" jobclass "value=" timer. Hotwatertask "></property> </bean> <!--Configure a trigger--> <bean id=" Hotwatertrigger "class=" Org.springframework.scheduling.quartz.SimpleTriggerBean "> <property name=" jobdetail "ref=" Hotwatertask "> </property> <property name= "Startdelay" value= "3600000" ></property> <property name= " Repeatinterval "value=" 3600000 "></property> </bean>         <!--Total dispatch, for start timer--& Gt <bean id= "Schedulerfactory" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" > < Property name= "Triggers" > <list> <ref bean= "Hotwatertrigger"/> </list> </property> </ Bean>   See, here we do not declare a Hotwatertask  bean directly, but declare a jobdetailbean. This is the characteristic of quartz. JobdetailbeaN is a subclass of the quartz org.quartz.JobDetail that requires a job object to be set by Jobclass property.   Well, the above task has been implemented, below to see how to implement the specific date and date of the code executed in seconds
Quartz at a specified time (a powerful agent-timed execution mechanism)   (1) Define work alarm clock class code as follows: Package timer; /** * Start work, this program requires a daily (not weekend) Eight o'clock in the morning need to start once * @author Sam */public class Startworkjob {public void Startwork () {System.out. println ("I am working procedures, every day (not weekend) Eight o'clock in the morning need to start once"); System.out.println ("went to work.") ~"); } }
  See, this class Startworkjob   does not inherit any classes nor implements any interfaces, and the method   start work is also defined by itself, and the original business code does not need to make any changes. Here's a mechanism for implementing quartz, which implements a timed task with the proxy class (Methodinvokingjobdetailfactorybean) provided by spring, which only needs to provide the classes it wants to broker and the methods to proxy. Can be very good on the line regularly monitored, powerful bar, the relevant code is as follows: <!--Configure the Bean class that needs to be timed--> <bean id= "startworkjob" class= timer. Startworkjob "></bean>     <!--configuration tasks specific classes and methods--> <bean id=" Startworktask "class=" Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean "> <!--the bean--> to be invoked <property Name= "TargetObject" ref= "Startworkjob" ></property>  <!--the method to invoke--> <property " Targetmethod "value=" startwork ></property> <!--concurrency, false means that if an error occurs, it does not affect the next call--> <property name= " Concurrent "value= false" ></property> </bean> <!--Configure a trigger--> <bean id= "Startworktrigger" class= "Org.springframework.scheduling.quartz.CronTriggerBean" > <property name= "Jobdetail" Startworktask "></property> &LT;property name= "cronexpression" value= "0 * 13 * *?" ></property> <!--0 seconds per minute of 1 o'clock in the afternoon every day--> </bean>   <!--total schedule, for starting timer--> <bean id= " Schedulerfactory "class=" Org.springframework.scheduling.quartz.SchedulerFactoryBean "> <property name=" Triggers "> <list> <ref bean=" Startworktrigger "/> </list> </property> </bean>   & nbsp;      Well, a timed trigger task that specifies a specific time has been implemented, and here's a look at the configuration information that Cronexpression needs to know, as follows: A cron expression has a space-delimited time element of at least 6 (or possibly 7). From left to right:

1. Seconds 2 minutes 3 hours 4. Month (1-31) 5. Month (1-12 or JAN-DEC) 6. Days of the week (1-7 or Sun-sat) 7. Year (1970-2099)
Each element displays a specified value (such as 6), an interval (9-12), a list (9,11,13), or a wildcard character (*). Because 4 and 6 of these two elements are mutually exclusive, you should set a question mark (. To indicate the field that you do not want to set, "/" if the combination of values indicates the number of repetitions (10/6 means repeat 6 times every 10 seconds).
Examples are as follows: 0 0 * *?---------------triggered every day 12:00 noon
0 15 10? * *---------------Trigger every 10:15
0 * *?---------------triggered 10:15 daily
0 15 10 * *? *---------------Trigger every 10:15
0 15 10 * *? The---------------of the 2005 is triggered every day of the year, 10:15
0 * * *?---------------each day from 2:00 to 2:59 every minute
0 0/5 * *?---------------is triggered every 5 minutes between 2:00 and 2:59 daily
0 0/5 14,18 * *?---------------is triggered every 5 minutes between 2:00 to 2:59 and 6:00 to 6:59 every day
0 0-5 * *?---------------each day from 2:00 to 2:05 per minute
0 10,44 14? 3 WED---------------every March Wednesday at 2:00 and 2:44
0 15 10? * Mon-fri---------------triggers from Monday to Friday daily 10:15
0 *?---------------triggered every 15 days of the month at 10:15
0 L *?---------------triggered at 10:15 on the last day of each month
0 15 10? * 6L---------------triggered at the last Friday of every month, 10:15
0 15 10? * 6L 2002-2005---------------in 2002, 2003, the last Friday of the month of 2005.
0 15 10? * 6#3---------------triggered on the third Friday of every month, 10:15
0 0 1/5 *?---------------from the first day of each month, every 5 days 12:00 noon.

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.