quartz--Task Scheduling

Source: Internet
Author: User
Tags date1 sleep
Task Scheduling:At a certain point in time or at intervals to do something, alarm clock, planning, planning tasks, timed mail .... All belong to the dispatch of affairs. The previous use of WinForm timer or JS setinterval () and settimeout () can also achieve a simple scheduling
Quartz framework is a Java task scheduling an excellent solution, official website: The Http://quartz-scheduler.org/Quartz framework of the three major core: Planning Tasks: The action to do triggers: Defining the time to do Dispatch Device: Associate management of a task with a trigger
Use steps: Create the project and write the corresponding business operations Add quartz rack package to project, mainly have the following rack package
Commons-dbcp-1.3.jar
Commons-pool-1.5.4.jar
Log4j-1.2.14.jar
Slf4j-api-1.6.0.jar
Slf4j-log4j12-1.6.0.jar
Quartz-all-1.8.6.jar
Create the implementation class for the job interface and invoke the business operation in the method it implements


public class Remindjob implements Job {
/**

* The business category of the specific things like

*/
Private Remindservice service;

@Override
public void execute (jobexecutioncontext context) throws Jobexecutionexception {

Jobdetail Detail=context.getjobdetail ();
Service= (Remindservice) Detail.getjobdatamap (). Get ("service");
String username= Detail.getjobdatamap (). GetString ("username");
Service.remind (username);//calling Specific business methods
}


}
Create a test class (on-demand when it is actually used), in which the actual plan task Jobdetail
Define triggers Trigger define Scheduler Scheduler use Scheduler to associate scheduled Tasks with triggers start scheduler
(4 step --8 Step) Example one : Implement simple trigger rules with Simpletrigger

/**

* Simple Implementation

*/
public class Remindjobtest {

@Test
public void Test () throws Exception {

Create Job
Jobdetailimpl job=new Jobdetailimpl ("Work", "remind", Remindjob.class);
Job.getjobdatamap (). Put ("username", "Nie Lei");
Job.getjobdatamap (). Put ("service", New Remindservice ());
Create Trigger: Use Simpletrigger

Function: Specified interval and number of times
Simpletrigger trigger=new Simpletriggerimpl ("Worktrigger"),
"Remind", simpletriggerimpl.repeat_indefinitely, 3000);

Create Scheduler
Schedulerfactory sf=new stdschedulerfactory ();
Scheduler Sche=sf.getscheduler ();
Association
Sche.schedulejob (Job, trigger);
Start
Sche.start ();
Thread.Sleep (10000);
Sche.shutdown ();
}
}
(4 step --8 Step) Example two : Implement a trigger with a crontrigger to specify a complex time point

@Test
public void Testcrontrigger () throws Exception {

Create Job

Jobdetailimpl job=new Jobdetailimpl ("Work", "remind", Remindjob.class);
Job.getjobdatamap (). Put ("username", "Nie Lei");
Job.getjobdatamap (). Put ("service", New Remindservice ());
Create Trigger
Simpletrigger trigger=new Simpletriggerimpl ("Worktrigger", "remind",

simpletriggerimpl.repeat_indefinitely, 3000);

Using a Crontrigger trigger, a cron expression is used to describe a batch-specified point in time.

More flexible than Simpletrigger: This is 2014 every Tuesday three o'clock in the afternoon 48 minutes, every three seconds to do something
Crontriggerimpl trigger=new Crontriggerimpl ("Worktrigger", "remind",

"0/3 48 15?" * TUE 2014 ");


Create Scheduler
Schedulerfactory sf=new stdschedulerfactory ();
Scheduler Sche=sf.getscheduler ();
Association
Sche.schedulejob (Job, trigger);
Start
Sche.start ();
Thread.Sleep (10000);
Sche.shutdown ();

}
(4 step --8) Example two : remove the specified date with calendar on the basis of Crontrigger

@Test
public void Testcalendar () throws Exception {

Create Job

Jobdetailimpl job=new Jobdetailimpl ("Work", "remind", Remindjob.class);
Job.getjobdatamap (). Put ("username", "Nie Lei");
Job.getjobdatamap (). Put ("service", New Remindservice ());
Create Trigger
Crontriggerimpl trigger=new Crontriggerimpl ("Worktrigger", "remind",
"* * 16?" * TUE 2014 ");

Create calendar: A variety of ways;
Annualcalendar cal=new Annualcalendar ();
Calendar day=calendar.getinstance ();

Day.set (Calendar.day_of_year, 2014); Set year
Day.set (Calendar.day_of_month, calendar.july); Adjust the month
Day.set (Calendar.day_of_week, calendar.tuesday); Set a specific day to exclude
Day.settime (New Date ()); Setting excludes specific one day
Day.set (2014, Calendar.june, 10); Setting excludes specific one day
Cal.setdayexcluded (day, true);


Create Scheduler
Schedulerfactory sf=new stdschedulerfactory ();
Scheduler Sche=sf.getscheduler ();
Sche.addcalendar ("Mycal", Cal, True, true);
Trigger.setcalendarname ("mycal");
Association
Sche.schedulejob (Job, trigger);
Start
Sche.start ();
Thread.Sleep (1000000000);
}


Cron expression:

A cron expression is used to configure an Crontrigger instance. A cron expression is a 7-subexpression string. Each subexpression describes a separate schedule detail.

These subexpression are separated by a space, respectively, to indicate:

1. Seconds seconds

2. Minutes minutes

3. Hours hours

4. Days of the Day-of-month month

5. Month Month

6. Days of the Day-of-week week

7. Year (optional field) (optional field)


s M h Dom m Dow Y

1 2 3 4 5 6 7


Order: Right to Left, [year] Zhou seconds

Symbol:

* Each possible value

/ Increment A/b from the beginning of every time to increase the B. or interval

? No value

L Last value

# The first few weeks of the month, 6#3 third Friday

- Continuous range to

, Multiple values

The W character is used to specify the closest week (specified in the Day-of-week field) to the distance.


wildcard characters:

' * ' can be used to represent "every" possible value in the domain. Therefore, the * in the Month field represents each month, while the * in the Day-of-week field represents "Every day of the week".

Values in all domains have a specific legal scope, and the legal scope of these values is quite obvious, for example: the legal value of seconds and domains is 0 toone, and the legal range of hours is 0 toDay-of-month, which is worth the legal scope of 0 to, but be aware of the different days in different months. The legal value of the month is 0 toone. Or with a string Jan,feb MAR, APR, May, June, April, AUG, SEP, OCT, NOV and DEC. Days-of-week can be expressed in 1 to 7 (1= Sunday) or by a string of sun, MON, TUE, WED, THU, FRI, and Sat.


The '/' character is used to represent the increment of the value, for example, if you put ' 0/15 ' in the minute field, it means "every 15 minutes, starting from 0," If you use ' 3/20 ' in a part of a field, it means "every 20 minutes in the hour, starting at the 3rd minute" or another form of ' 3, 23,43 '.


' ? ' characters can be used in Day-of-month and Day-of-week fields, which are used to indicate ' no value specified '.

This is useful if you need to specify a value for one or two fields without having to set up a different domain. See the example below (and Crontrigger JavaDOC) more clearly.


The ' L ' character can be used in Day-of-month and Day-of-week, which is shorthand for "last," but is different in two domains. For example, "L" in the Day-of-month domain represents the last day of the month, that is, 31st of January, the 28th of February, which is not a leap year. If it is used in day-of-week, it means "7" or "SAT". However, if the character follows a different value in the Day-of-week field, it means "last week XXX of the month". For example, "6L" or "Fril" all represent the last Friday of this month. When using the ' L ' option, the most important thing is not to specify a list or range of values, otherwise it can cause confusion.


The ' W ' character is used to specify the nearest week (specified in the Day-of-week field) for the distance. For example, if you specify "15W" for the Day-of-month field, it means "the nearest week from 15th in the month".


' # ' represents the week ordinal of the month. For example, "6#3" or "fri#3" in the Day-of-week field means "the third Friday of the month". Here are some expressions and their meanings, and you can find more examples in Crontrigger's Javadoc.


An example of Example Cron Expressions--cron expressions

Crontrigger case A simple expression that triggers once every 5 minutes
"0 0/5 * * *?"

Crontrigger example 2– An expression that fires every 5 minutes after 10 seconds per minute (for example,. 10:00:10 am, 10:05:10, etc.).
"10 0/5 * * *?"

Crontrigger Example 3 – An expression triggered in each of the Wednesday and Friday 10:30,11:30,12:30.
"0 30 10-13?" * Wed,fri "

The Crontrigger case 4– is triggered every half hour between 8 and 10 points per month of 5th, 20th, and does not include 10 dots//, just 8:30,9:00 and 9:30 expressions.
"0 0/30 8-9 5,20 *?"

Note that for individual triggers, some schedule requirements may be too complex to be expressed in an expression, for example:
It triggers every 5 minutes between 9:00 and 10:00, and 1:00 to 10 points every 20 minutes.
The solution is to create two triggers and two triggers to run the same task.


configuration Quartz in Spring

Mode one:

Create projects, import Spring-core with spring-persistence and quartz, and write the appropriate business classes

public class Remindserviceimpl implements Iremindservice {

@Override
public void remind (String username) {
System.out.println (username+ "Move the bricks!) The foreman is looking for you!"
}

}

Create the implementation class that creates the job interface and invoke the business operation in the method that it implements

public class Remindjob extends Quartzjobbean {

Private Iremindservice service;

public void Setservice (Iremindservice service) {
This.service = Service;
}

@Override
protected void Executeinternal (Jobexecutioncontext context)
Throws Jobexecutionexception {
Jobdetail Detail=context.getjobdetail ();
String username= Detail.getjobdatamap (). GetString ("username");
Service.remind (username);
}

}
Configure scheduled Tasks, triggers, scheduler in spring's configuration file

<?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.1.xsd ">

<!--service-->
<bean name= "service" class= "service. Remindserviceimpl "/>

<!--job-->
<bean name= "Job" class= "Org.springframework.scheduling.quartz.JobDetailBean" >
<property name= "group" value= "Group1"/>
<property name= "name" value= "Work"/>
<property name= "Jobclass" value= "job. Remindjob "></property>
<property name= "Jobdataasmap" >
<map>
<entry key= "username" value= "Nie Lei"/>
<entry key= "service" value-ref= "service"/>
</map>
</property>
</bean>
<!--calendar-->
<bean name= "Calendar" class= "Org.quartz.impl.calendar.AnnualCalendar" >
<property name= "daysexcluded" >
<list>

<!--here Configure: to generate a class of objects using the factory method-->
<bean class= "Java.util.GregorianCalendar" factory-method= "getinstance" >
<property name= "Time" >
<bean class= "Java.util.Date" ></bean>
</property>
</bean>
</list>
</property>
</bean>
<!--Trigger Here are two definitions of triggers, whichever is-->
<bean name= "trigger" class= "Org.springframework.scheduling.quartz.SimpleTriggerBean" >
<property name= "name" value= "Mytrigger"/>
<property name= "group" value= "Group1"/>
<property name= "RepeatCount" value= "-1"/>
<property name= "Repeatinterval" value= "1000"/>
<property name= "Jobdetail" ref= "Job"/>
</bean>
<bean name= "Trigger1" class= "Org.springframework.scheduling.quartz.CronTriggerBean" >
<property name= "name" value= "Mytrigger"/>
<property name= "group" value= "Group1"/>
<property name= "cronexpression" value= "0/5 * * * *?"/>
<property name= "Jobdetail" ref= "Job"/>

<!--the name value of the calendar corresponding to the configuration trigger is a string value-->
<property name= "calendarname" value= "Calendar"/>
</bean>
<!--Scheduler-->
<bean name= "Schedule" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >
<property name= "calendars" ><!--Association calendars-->
<map>
<entry key= "Calendar" value-ref= "Calendar"/>
</map>
</property>
<property name= "triggers" ><!--association triggers-->
<array>
<ref bean= "Trigger1"/>
</array>
</property>
</bean>
</beans>

Mode two:

Create projects, import Spring-core and spring-persistence and quartz, and write the appropriate business classes, as above configure scheduled tasks in the spring configuration file, triggers, scheduler

<!--job and the way it is configured here are different from this

The Methodinvokingjobdetailfactorybean class is used here.

It's using the

-->
<bean name= "Job" class= "Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
<property name= "group" value= "group1"/><!--meaningless, can be omitted-->
<property name= "name" value= "work"/><!--meaningless, can be omitted-->
<property name= "TargetObject" ref= "service"/><!--the target class to perform the scheduled task-->
<property name= "Targetmethod" value= "remind"/><!--target method-->
<property name= "Arguments" ><!--the required parameters for the target method-->
<array>
<value> John </value>
</array>
</property>

</bean> Note: In the integration with spring, you need to filter the configuration of a particular day

<!--calendar-->
<bean name= "Date1" class= "Java.util.Date" >
<property name= "Date" value= "one"/><!--1-31-->
<property name= "Month" value= "5"/><!--0-11, this film is June-->
<property name= "Year" value= "114"/><!--starting from 1900, this is 2014, Direct 2014 is also OK-->
</bean>
<bean name= "Calendar" class= "Org.quartz.impl.calendar.AnnualCalendar" >
<property name= "daysexcluded" >
<list>
<bean class= "Java.util.GregorianCalendar" factory-method= "getinstance" >
<property name= "Time" ref= "Date1"/>
</bean>
</list>
</property>
</bean>

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.