Quartz.net open-source job scheduling framework and quartz.net

Source: Internet
Author: User

Quartz.net open-source job scheduling framework and quartz.net
Preface

The quartz.net job scheduling framework is an extended. net porting version of the quartz scheduler project developed by OpenSymphony. Supports cron-like expressions, clusters, and databases. Not to mention its powerful functionality.

Download project documentation Official Website: http://www.quartz-scheduler.net/

Common. Logging. dll, Common. Logging. Core. dll, and Quartz. dll must be referenced in the project.

The following is a small project I recently developed about scheduler scheduling to help you understand the functions and common methods of quartz.net.


 

Quartz.net simple usage-getting started

If you are a beginner in quartz.net, the console is getting started here,SuggestionsSo easy to understand quartz.net in 10 minutes.

1. Create a scheduler that runs every three seconds:

public class RunMain
    {
        static void Main (string [] args)
        {
            Console.WriteLine (DateTime.Now.ToString ("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 job scheduling pool
            sched.ScheduleJob (job, trigger);
            // 5. Start running
            sched.Start ();
            Console.ReadKey ();
        }
    }
    public class JobDemo: IJob
    {
        /// <summary>
        /// Here is the method of executing the job schedule every time
        /// </ summary>
        /// <param name = "context"> </ param>
        public void Execute (IJobExecutionContext context)
        {
            Console.WriteLine (DateTime.Now.ToString ("r"));
        }
    }
Note: 1. Write down the order of job scheduling creation. 2. The result of the above code execution is that the Execute in JobDemo is executed every three seconds. If the program does not stop, it will be executed endlessly and endlessly.

2. Improvement (rich scheduling plan): Last job, I want him to execute it every three seconds for a total of 100 times. The start time is set at the current time, and the end time is set after 2 hours, but 100 times No more than 2 hours after execution.

public class RunMain {static void Main (string [] args) {Console.WriteLine (DateTime.Now.ToString ("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 current time of the table name is delayed by 2 seconds 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 job scheduling pool sched.ScheduleJob (job, trigger); // Start running sched.Start (); Console.ReadKey ();}} public class JobDemo: IJob {/// <summary> /// This is the method of job scheduling every time it is executed /// / </ summary> /// <param name = "context"> </ param> public void Execute (IJobExecutionContext context) {Console.WriteLine (DateTime.Now.ToString ("r"));}} View Code
3. Continue to improve (cron-like use): the first two job schedules are too simple, if I want to be at the 10th, 20th, 25th, 26th, 33th, 54th minute of each hour, the 1st, 10th, and 14th minute Once every second. Then the above is obviously unsatisfactory. This is how I introduced cron-like expressions to achieve various time and latitude calls.

 public class RunMain
    {
        static void Main (string [] args)
        {
            Console.WriteLine (DateTime.Now.ToString ("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 current time of the table name is delayed by 2 seconds.
            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 job scheduling pool
            sched.ScheduleJob (job, trigger);
            //start operation
            sched.Start ();
            // hang for 2 days
            Thread.Sleep (TimeSpan.FromDays (2));
            // Close job scheduling after 2 days, will not be executed
            sched.Shutdown ();
            Console.ReadKey ();
        }
    }
    public class JobDemo: IJob
    {
        /// <summary>
        /// Here is the method of executing the job schedule every time
        /// </ summary>
        /// <param name = "context"> </ param>
        public void Execute (IJobExecutionContext context)
        {
            Console.WriteLine (DateTime.Now.ToString ("r"));
        }
    }
Detailed explanation of job scheduling project based on Quartz.net
The final effect is shown in the first figure at the beginning.

The following mainly talks about how to locate specific job scheduling in job scheduling, and group, name, add, start, and stop job scheduling.

First show the structure of the table below. In the project, I call job scheduling as task scheduling.


1. New job scheduling.

 /// <summary>
        /// mission plan
        /// </ summary>
        public static IScheduler scheduler = null;
        public static IScheduler GetScheduler ()
        {
            if (scheduler! = null)
            {
                return scheduler;
            }
            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 = DateTime.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 <HttpJob> ()
                      .WithIdentity (m.JobName, m.JobGroup)
                      .Build ();
                    ICronTrigger trigger = (ICronTrigger) TriggerBuilder.Create ()
                                                 .StartAt (starRunTime)
                                                 .EndAt (endRunTime)
                                                 .WithIdentity (m.JobName, m.JobGroup)
                                                 .WithCronSchedule (m.CronStr)
                                                 .Build ();
                    scheduler.ScheduleJob (job, trigger);
                    scheduler.Start ();
                    StopScheduleJob (m.JobGroup, m.JobName);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                //DoApplication.WriteLogFile(ex.Message + "\ r \ n" + ex.StackTrace);
                return false;
            }
        }
Note: 1. The functions of job scheduling are as follows. 2. The WithIdentity (m.JobName, m.JobGroup) above is to add a group and name to the job schedule, which is convenient for us to start and stop for which job plan.

 

public class HttpJob: IJob {public void Execute (IJobExecutionContext context) {ThreadPool.QueueUserWorkItem (delegate (Object o) {try {//DoApplication.WriteLogFile(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. Executing)); 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.Na me, RunStatus = (int) ADJ.Job.Entity.EnumType.JobRunStatus. To be run}); if (result.Code == 1) {#region join the execution details WJ_ScheduleDetailsEntity dm = new WJ_ScheduleDetailsEntity (); dm.ActionDescribe = " Execution completed: "+ result.Message; dm.ActionStep = (int) ADJ.Job.Entity.EnumType.JobStep. Execution 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 add execution details WJ_ScheduleDetailsEntity dm = new WJ_ScheduleDetailsEntity (); dm.ActionDescribe = " In the execution task plan, the execution plan process is in error. "+ Result.Message; dm.ActionStep = (int) ADJ.Job.Entity.EnumType.JobStep. In the execution task 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 add execution details WJ_ScheduleDetailsEntity dm = new WJ_ScheduleDetailsEntity (); dm.ActionDescribe = "In the execution of the task plan, the execution plan process error:" + ex.Message + "/ r / n" + ex.StackTrace; dm.ActionStep = (int ) ADJ.Job.Entity.EnumType.JobStep. Execution task planning; 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);}});}} View Code
note: The IJobExecutionContext parameter of the Execute method executed here will automatically bring in the details of the job scheduling, job name, job group name, job next execution time, job execution time, etc. The content here is also crucial, For example, according to the job group and job name, we can find the corresponding job scheduling details from the database and update the operation database.

2. Stop and start a certain operation plan.

 /// <summary>
        /// Pause the specified task plan
        /// </ summary>
        /// <returns> </ returns>
        public JsonResult StopScheduleJob (string jobGroup, string jobName)
        {
            try
            {
                scheduler = 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. has been stopped});
                return Json (new StatusView () {Status = 0, Msg = "Stop mission planning successful!"}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                DoApplication.WriteLogFile (ex.Message + "/ r / n" + ex.StackTrace);
                return Json (new StatusView () {Status = -1, Msg = "Stopping the task will fail the plan!"}, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// Open the specified task plan
        /// </ summary>
        /// <returns> </ returns>
        public JsonResult RunScheduleJob (string jobGroup, string 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. is enabled;
                new WJ_ScheduleManage (). UpdateScheduleStatus (sm);
                scheduler = GetScheduler ();
                scheduler.ResumeJob (new JobKey (jobName, jobGroup));
                return Json (new StatusView () {Status = 0, Msg = "Startup succeeded!"}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
              
                DoApplication.WriteLogFile (ex.Message + "/ r / n" + ex.StackTrace);
                return Json (new StatusView () {Status = -1, Msg = "Startup failed!"}, JsonRequestBehavior.AllowGet);
            }
        }
Final note:

1. This project completely uses cron-like expressions to implement trigger configuration. If you do n’t know cron, then I have introduced cron in the previous article. If you do n’t know cron and do n’t have a suitable generation tool, then Enter the 2 groups on the upper left and find me.

2. This project is deployed in IIS, then the recycling mechanism of the application pool must be set to never recycle, under configuration, if it will not be configured, enter the 2 groups on the upper left and find me.

Related Article

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.