Spring Quartz for task scheduling

Source: Internet
Author: User

Task scheduling

In enterprise applications, There are often "scheduled tasks", that is, at a certain point in time to do something at the core is to focus on time, that is, at a specific point in time, the system performs a specified operation task scheduling involves multi-threaded concurrency, thread pool maintenance, run time rule resolution, run-site protection to restore and other aspects The quartz framework is an open source Enterprise-level task scheduling service that has been used as a good solution for task Scheduling.

Quartz Framework Core

Quartz has highly abstracted the task scheduling, proposes 3 core concepts, and describes the interfaces and classes in the Org.quartz package.

Task: is the work Done. Quartz provides a job interface to support task definitions

Trigger: defines the time-triggered rule that triggers job Execution. Quartz provides a trigger class and its subclasses support trigger functionality

Scheduler: Quartz provides a scheduler interface that binds work tasks and triggers to ensure that tasks can be performed at the right time

Operating Environment

Task scheduling

Task execution

Persistence of tasks

Transaction

Cluster

Listener and insert

Quartz case

1. Locate the jar package for the quartz framework

2. Start creating templates for Entity layer definition tasks

Package Cn.entity;public class Plan {      //time    private String date;    Task    Private String task;        Public Plan () {        Super ();    }        Public Plan (string date, string task) {        Super ();        This.date = date;        This.task = task;    }    @Override public    String toString () {        return "Plan [date=" + date + ", task=" + task + "]";    }    Public String getDate () {        return date;    }    public void SetDate (String Date) {        this.date = date;    }    Public String gettask () {        return task;    }    public void Settask (String task) {        this.task = task;    }    }

3. Customizing a generic collection The user stores multiple plan objects, providing a way to read the data in the generic collection

Package Cn.service;import Java.util.arraylist;import Java.util.list;import cn.entity.plan;/** * Reminder Service class * @author *  * /public class Remindservice {     //01. Create a collection, and the method return value is a collection type public    list<plan> getplansfortoday () {        list<plan> list=new arraylist<plan> ();        Plan plan1=new plan ("December 16, 2016", "2016 last one months");        Plan plan2=new plan ("December 18, 2016", "Quartz");                List.add (plan1);        List.add (plan2);                return list;    }            02. the method used to print the reminder content in the collection public    void Printmessage () {        list<plan> List = getplansfortoday ();        For (plan plan:list) {            //individual plan            System.out.println ("scheduled time" +plan.getdate () + "\ t plan content" +plan.gettask ());        }    }}

4. Reminding the Business class

Package Cn.quartz;import Org.quartz.job;import Org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;import cn.service.remindservice;/** * Remind Business * @author  * *///to make a normal class into plan public Class Remindjob implements JOB {    //implant service object    private Remindservice service=new remindservice ();    @Override public    Void execute (jobexecutioncontext Context) throws Jobexecutionexception {        Service.printmessage ();    }    Public Remindservice getService () {        return service;    }    public void Setservice (remindservice service) {        this.service = service;    }    }

There is only one execute () method in the job interface that implements the method in the implementation class to perform specific tasks.

5. Real task objects and trigger objects

Package Cn.test;import Java.util.date;import Org.quartz.cronschedulebuilder;import org.quartz.crontrigger;import Org.quartz.datebuilder;import Org.quartz.jobbuilder;import Org.quartz.jobdetail;import org.quartz.Scheduler; Import Org.quartz.schedulerexception;import Org.quartz.schedulerfactory;import org.quartz.SimpleScheduleBuilder; Import Org.quartz.trigger;import Org.quartz.triggerbuilder;import Org.quartz.triggerkey;import Org.quartz.impl.stdschedulerfactory;import Cn.quartz.remindjob;public class myquartztest {public static void tool ( ) throws schedulerexception, Interruptedexception{//first Step Build job Jobdetail job = Jobbuilder.newjob (REMINDJOB.C                  lass)//. withidentity ("job1", "group1")//. Build (); Step two create trigger//the first way control is not good/* Date runTime = datebuilder.evenminutedate (new Date (system.currenttimemilli         S ()));        Trigger Trigger = Triggerbuilder.newtrigger (). withidentity ("trigger1", "group1")//         . startAt (runTime). Build (); *//the second way is not very good/*trigger Trigger = Triggerbuilder.newtrigger ( ). withidentity (triggerkey.triggerkey ("mytrigger", "mytriggergroup")). withschedule (simpl                 Eschedulebuilder.simpleschedule (). withintervalinseconds (2). repeatforever ())                                               . startAt (new Date (system.currenttimemillis () +2000)). build (); */            Step three bind job and trigger//first we must get a reference to a scheduler//create dispatcher factory          Schedulerfactory SF = new Stdschedulerfactory ();          Create a dispatcher Scheduler sched = Sf.getscheduler ();          Register and schedule Sched.schedulejob (job, trigger);            Start scheduling Sched.start ();             /*thread.sleep (3000); *//close Dispatch Sched.shutdown (); */} public static void main (string[] Args) throws Schedulerexception, interruptedexception {tool ();    System.out.println ("hehe"); }}

The first way:

The second way:

6. Using Crontrigger

Crontrigger is also a trigger subclass.

Comparison of Crontrigger and Simpletrigger

Crontrigger allows users to more accurately control the running date and time of a task, rather than just the frequency of work defined

Crontrigger defines the exact run-time point through a cron Expression. The syntax for creating Crontrigger is as Follows:

7.Cron-expression

To use crontrigger, you must master cron expressions

A cron expression consists of a 6~7 of time elements separated by Spaces. The 7th element is optional

Each field of a cron expression can explicitly specify a value (such as 49), a range (such as 1-6), a list (such as 1,3,5), or a wildcard character (such as *)

The 8.Cron expression has several special characters, which are described below

"-": underlined to indicate a range

",": data with comma interval, representing a list

"*": represents each value, which can be used for all FIELDS. For example, the hour field represents hourly

“ ? ” : This character is used only for the day of the month field and the days of the week field, indicating that no value is specified

"/": usually expressed as the starting value of x/y,x, and Y represents the increment of the Value.

"L": indicates the last day, only used in date and week fields

"#": can only be used for the "day of the week" field, which represents the first few weeks of the Month. For example: "6#3" means the third Friday of this month

9.Cron Expression Cases

Test:

Package Cn.test;import Java.util.date;import Org.quartz.cronschedulebuilder;import org.quartz.crontrigger;import Org.quartz.datebuilder;import Org.quartz.jobbuilder;import Org.quartz.jobdetail;import org.quartz.Scheduler; Import Org.quartz.schedulerexception;import Org.quartz.schedulerfactory;import org.quartz.SimpleScheduleBuilder; Import Org.quartz.trigger;import Org.quartz.triggerbuilder;import Org.quartz.triggerkey;import Org.quartz.impl.stdschedulerfactory;import Cn.quartz.remindjob;public class myquartztest {public static void tool ( ) throws schedulerexception, Interruptedexception{//first Step Build job Jobdetail job = Jobbuilder.newjob (REMINDJOB.C                  lass)//. withidentity ("job1", "group1")//. Build (); Step two Create trigger/** * 2016 third Saturday 10:18 Trigger 0 18 10? * 6#3 */crontrigger trigger=triggerbuilder.newtrigger ()//. withidentity ("mytrigger", " Mytriggergroup ")//.Withschedule (cronschedulebuilder.//cronschedule ("0 18 10?                              * 6#3)). Build (); Step three bind job and trigger//first we must get a reference to a scheduler//create dispatcher factory SCHEDULERFAC          Tory SF = new Stdschedulerfactory ();          Create a dispatcher Scheduler sched = Sf.getscheduler ();          Register and schedule Sched.schedulejob (job, trigger);              Start scheduling Sched.start ();        public static void main (string[] Args) throws schedulerexception, interruptedexception {tool ();    System.out.println ("hehe"); }}

Spring Quartz for task scheduling

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.