Quartz.net Open Source Job scheduling framework use detailed

Source: Internet
Author: User

Objective

The Quartz.net job scheduling framework is a. NET extended ported version of the Quartz Scheduler project developed by the great organization Opensymphony. Supports cron-like expressions, clusters, databases. Features are powerful, let alone.

Download Project documents official website: http://www.quartz-scheduler.net/

References in the project: Common.Logging.dll, Common.Logging.Core.dll, Quartz.dll

Now let's break down a little project I've done recently on scheduling, to help understand the quartz.net and common methods.

Simple usage of quartz.net-Getting Started

If you are a novice to quartz.net, console starter Here, it is recommended to follow the next, then 10 minutes to understand quartz.net is so easy to do.

1. Create a scheduled schedule that executes every 3 seconds

public class Runmain {static void Main (string[] args) {Console.WriteLine (DateTime.Now.ToStri            Ng ("R"));            1. First create a job scheduling pool ischedulerfactory Schedf = new Stdschedulerfactory (); IScheduler sched = Schedf.            Getscheduler (); 2. Create a specific job ijobdetail job = jobbuilder.create<jobdemo> ().                       Build (); 3. Create and configure a trigger Isimpletrigger trigger = (Isimpletrigger) triggerbuilder.create (). Withsimpleschedule (X=>x.withintervalinseconds (3). Withrepeatcount (int. MaxValue)).            Build (); 4. Join the sched in the job scheduling pool.            Schedulejob (Job, trigger); 5. Start running sched.            Start ();        Console.readkey (); }} public class Jobdemo:ijob {//<summary>///This is the job schedule per time execution method///&LT;/SUMMARY&G        T            <param name= "context" ></param> public void Execute (Ijobexecutioncontext context) { Console.writEline (DateTime.Now.ToString ("R")); }    }

Note:1, note the order in which the job schedule was created. 2, the above code execution result is, every three seconds executes once jobdemo in the Execute, if the program does not stop, the endless execution to the everlasting, hehe, tore the egg.

2. Improved (Rich scheduling): The last job, I want him to execute every three seconds, a total of 100 times, start execution time set at the current time, the end time I set in 2 hours, but 100 times executed no more than 2 small time is no longer executed.

    public class Runmain {static void Main (string[] args) {Console.WriteLine (DateTime.Now.To            String ("R"));            First create a job scheduling pool ischedulerfactory Schedf = new Stdschedulerfactory (); IScheduler sched = Schedf.            Getscheduler (); Create a specific job ijobdetail job = jobbuilder.create<jobdemo> ().            Build ();            Nextgivenseconddate: If the first parameter is null, the table name is delayed by 2 seconds later in the current time.            DateTimeOffset startTime = Datebuilder.nextgivenseconddate (DateTime.Now.AddSeconds (1), 2);            DateTimeOffset endTime = Datebuilder.nextgivenseconddate (DateTime.Now.AddHours (2), 3); Create and configure a trigger Isimpletrigger trigger = (Isimpletrigger) triggerbuilder.create (). StartAt (StartTime). EndAt (EndTime). Withsimpleschedule (X=>x.withintervalinseconds (3). Withrepeatcount (100)).            Build (); Join the sched in the job scheduling pool. ScheduleJob (job, trigger); Start Running sched.            Start ();        Console.readkey (); }} public class Jobdemo:ijob {//<summary>///This is the job schedule per time execution method///&LT;/SUMMARY&G        T            <param name= "context" ></param> public void Execute (Ijobexecutioncontext context) {        Console.WriteLine (DateTime.Now.ToString ("R")); }    }

3. Continue to improve (Cron-like use): The first two job scheduling is too simple, if I want to 10,20,25,26,33,54 minutes per hour, every minute of the 1th, 10, 14 seconds to execute once. So the above is obviously not enough. This is when I introduce the cron-like expression in order to achieve a variety of time-latitude calls.

 public class Runmain {static void Main (string[] args) {Console.WriteLine (DateTime.Now.ToStr            ING ("R"));            First create a job scheduling pool ischedulerfactory Schedf = new Stdschedulerfactory (); IScheduler sched = Schedf.            Getscheduler (); Create a specific job ijobdetail job = jobbuilder.create<jobdemo> ().            Build ();            Nextgivenseconddate: If the first parameter is null, the table name is delayed by 2 seconds later in the current time.            DateTimeOffset startTime = Datebuilder.nextgivenseconddate (DateTime.Now.AddSeconds (1), 2);            DateTimeOffset endTime = Datebuilder.nextgivenseconddate (DateTime.Now.AddYears (2), 3); Create and configure a trigger Icrontrigger trigger = (Icrontrigger) triggerbuilder.create (). StartAt (StartTime). EndAt (EndTime).                                        Withcronschedule ("1,10,14 10,20,25,26,33,54 * * *?") .            Build (); Join the sched in the job scheduling pool.            Schedulejob (Job, trigger);      Start running      Sched.            Start ();            Hangs 2 days Thread.Sleep (Timespan.fromdays (2)); After 2 days, the job schedule is closed and sched is not executed.            Shutdown ();        Console.readkey (); }} public class Jobdemo:ijob {//<summary>///This is the job schedule per time execution method///&LT;/SUMMARY&G        T            <param name= "context" ></param> public void Execute (Ijobexecutioncontext context) {        Console.WriteLine (DateTime.Now.ToString ("R")); }    }
A detailed description of job scheduling project based on Quartz.net

The final effect is shown in the first diagram that begins.

The following is mainly said, job scheduling in how to locate the specific job scheduling, and to the job scheduling group, name, add, start, stop.

First show the following table structure, in the project I call job scheduling for task scheduling.

1, new job scheduling.

 <summary>///Task Scheduler///</summary> public static IScheduler scheduler = NULL; public static IScheduler Getscheduler () {if (scheduler! = NULL) {return SCH            Eduler;                } else {ischedulerfactory SCHEDF = new Stdschedulerfactory (); IScheduler sched = Schedf.                Getscheduler ();            Return sched;        }}///<summary>//Add Task Schedule///</summary>//<returns></returns>                public bool Addschedulejob (wj_scheduleentity m) {try {if (M! = null) {if (m.starruntime = = null) {M.starruntime = D                    Atetime.now;                    } DateTimeOffset starruntime = Datebuilder.nextgivenseconddate (m.starruntime, 1); if (M.endruntime = = nulL) {m.endruntime = DateTime.MaxValue.AddDays (-1);                    } DateTimeOffset endruntime = Datebuilder.nextgivenseconddate (m.endruntime, 1);                    Scheduler = Getscheduler (); Ijobdetail job = jobbuilder.create

Note:1. Here are the functions that the job schedule executes. 2. The above withidentity (M.jobname, M.jobgroup), is to give the job scheduling to join the group, and the name, convenient for us to work on which job schedule, start stop and so on.

 public class Httpjob:ijob {public void Execute (Ijobexecutioncontext context) {ThreadPool. QueueUserWorkItem (delegate (Object o) {try {//DOAPPLICATION.W Ritelogfile (context. JobDetail.Key.Group + "---" + context. JobDetail.Key.Name + "---" + DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "---" + context. NextFireTimeUtc.Value.DateTime.AddHours (8).                    ToString ("Yyyy-mm-dd HH:mm:ss")); var sm = new Wj_schedulemanage (). Getschedulemodel (New Wj_scheduleentity () {Jobgroup = context. JobDetail.Key.Group, JobName = context.                    JobDetail.Key.Name}); New Wj_schedulemanage (). Updateschedulerunstatus (New Wj_scheduleentity () {Jobgroup = context. JobDetail.Key.Group, JobName = context. jobdetail.key.name,runstatus= (int) ADJ.                    Job.Entity.EnumType.JobRunStatus. In execution}); Esbrequest req = new Esbrequest (SM. Servicecode, SM.                    Apicode); Dataresult result = req.Request (); New Wj_schedulemanage (). Updateschedulerunstatus (New Wj_scheduleentity () {Jobgroup = context. JobDetail.Key.Group, JobName = context. JobDetail.Key.Name, runstatus = (int) ADJ.                    Job.Entity.EnumType.JobRunStatus. To run}); if (result.  Code = = 1) {#region Add execution detail wj_scheduledetailsentity DM =                        New Wj_scheduledetailsentity (); Dm. Actiondescribe = "Execution Done:" + result.                        Message; Dm. Actionstep = (int) ADJ.                        Job.Entity.EnumType.JobStep. Implementation completed; Dm.                        Createtime = DateTime.Now; Dm. Jobgroup = context.                        JobDetail.Key.Group; Dm. JobName = context.                        JobDetail.Key.Name; Dm.                        issuccess = 1; New Wj_schedulemanage ().                        Addscheduledetails (DM); #endregion} else {#Region join execution Details wj_scheduledetailsentity DM = new wj_scheduledetailsentity (); Dm. Actiondescribe = "There was an error executing the planning process in the execution of the scheduled task." +result.                        Message; Dm. Actionstep = (int) ADJ.                        Job.Entity.EnumType.JobStep. Implementation of the Mission plan; Dm.                        Createtime = DateTime.Now; Dm. Jobgroup = context.                        JobDetail.Key.Group; Dm. JobName = context.                        JobDetail.Key.Name; Dm.                        issuccess = 0; New Wj_schedulemanage ().                        Addscheduledetails (DM); #endregion} new Wj_schedulemanage (). Updateschedulenexttime (New Wj_scheduleentity () {Jobgroup = context. JobDetail.Key.Group, JobName = context. JobDetail.Key.Name, Nexttime = context.                NextFireTimeUtc.Value.DateTime.AddHours (8)}); } catch (Exception ex) {#region Join execution details Wj_scheduledet Ailsentity DM= new Wj_scheduledetailsentity (); Dm. Actiondescribe = "An error occurred during the execution of the planning process:" + ex. Message + "/r/n" + ex.                    StackTrace; Dm. Actionstep = (int) ADJ.                    Job.Entity.EnumType.JobStep. Implementation of the Mission plan; Dm.                    Createtime = DateTime.Now; Dm. Jobgroup = context.                    JobDetail.Key.Group; Dm. JobName = context.                    JobDetail.Key.Name; Dm.                    issuccess = 0; New Wj_schedulemanage ().                    Addscheduledetails (DM); #endregion Doapplication.writelogfile (ex. Message + "\ r \ n" + ex.                StackTrace);        }            }); }    }

Note: The Execute method parameter Ijobexecutioncontext executed here will automatically bring the details of job scheduling, job name, job group name, job next execution time, job execution time and so on, where the content is also very important, such as according to the job group, Job name we can find the corresponding job schedule from the database detailed, update the operational database.

2, for a job schedule to stop, start.

 <summary>///suspension of designated task schedule///</summary>//<returns></returns> Pub Lic Jsonresult stopschedulejob (String jobgroup, String jobName) {try {schedu                                Ler = Getscheduler (); Scheduler.                Pausejob (New Jobkey (JobName, Jobgroup)); New Wj_schedulemanage (). Updateschedulestatus (New Wj_scheduleentity () {JobName = JobName, Jobgroup = jobgroup, Status = (int) ADJ.                               Job.Entity.EnumType.JobStatus. stopped}); Return Json (New Statusview () {Status = 0, MSG = "Stop task scheduled successfully!"            "}, Jsonrequestbehavior.allowget); } catch (Exception ex) {Doapplication.writelogfile (ex. Message + "/r/n" + ex.                StackTrace); Return Json (New Statusview () {Status =-1, MSG = "Stop task will fail to schedule!"            "}, Jsonrequestbehavior.allowget); }}///<summary>//To open the specified task schedule/// </summary>//<returns></returns> public Jsonresult runschedulejob (string jobgroup, Stri ng JobName) {try {var sm = new Wj_schedulemanage ().                Getschedulemodel (New Wj_scheduleentity () {JobName = JobName, Jobgroup = Jobgroup});                Addschedulejob (SM); Sm. Status = (int) ADJ.                Job.Entity.EnumType.JobStatus. Enabled; New Wj_schedulemanage ().                Updateschedulestatus (SM);                Scheduler = Getscheduler (); Scheduler.                Resumejob (New Jobkey (JobName, Jobgroup)); Return Json (New Statusview () {Status = 0, MSG = "started successfully!            "}, Jsonrequestbehavior.allowget); } catch (Exception ex) {Doapplication.writelogfile (ex. Message + "/r/n" + ex.                StackTrace); Return Json (New Statusview () {Status =-1, MSG = "Failed to start!            "}, Jsonrequestbehavior.allowget); }        }

Last Note:

1, this project completely uses the Cron-like expression to implement the trigger configuration, if you do not know about Cron, then I have a description of cron in the previous article, if you know about cron and do not have a suitable generator tool, then into the top left 2 groups, look for me.

2, this project is deployed in IIS, then set the application pool recycling mechanism for, never recycle, configuration, if not configured, into the top left 2 groups, find me.

Quartz.net Open Source Job scheduling framework use detailed (GO)

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.