Simple use of C# Quartz.Net scheduled tasks

Quoted from: https://www.cnblogs.com/chenyucong/p/6264739.html , for reference only.

Recently, I made a software to execute tasks regularly.

When executing a task, log4net will be used to record the log. If there are exceptions in the execution of the task, an email will be sent to the specified object.

What I do is to perform a task at 9:00 and 16:00 every day to record:

 

First, get Quartz.Net,

In fact, you can use the Nuget manager of vs2015 to download.

 

I made a QuartzHelper, but in the main program, I still need other code.

This is the code for QuartzHelper:

using Quartz;
using Quartz.Impl;

namespace Cong.Utility
{
    public class QuartzHelper
    {
        /// <summary>
        ///Perform tasks at intervals
        /// </summary>
        ///< typeparam name = "t" > task class must implement the IJob interface < / typeparam >
        ///< param name = "seconds" > time interval (unit: milliseconds) < / param >
        public static void ExecuteInterval<T>(int seconds) where T : IJob
        {
            ISchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = factory.GetScheduler();

            //IJobDetail job = JobBuilder.Create<T>().WithIdentity("job1", "group1").Build();
            IJobDetail job = JobBuilder.Create<T>().Build();

            ITrigger trigger = TriggerBuilder.Create()
                .StartNow()
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).RepeatForever())
                .Build();

            scheduler.ScheduleJob(job, trigger);

            scheduler.Start();
        }

        /// <summary>
        ///Specify a time to perform the task
        /// </summary>
        ///< typeparam name = "t" > task class must implement the IJob interface < / typeparam >
        ///< param name = "cronexpression" > cron expression, that is, the expression specifying the time point < / param >
        public static void ExecuteByCron<T>(string cronExpression) where T : IJob
        {
            ISchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = factory.GetScheduler();

            IJobDetail job = JobBuilder.Create<T>().Build();

            //DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(DateTime.Now.AddSeconds(1), 2);
            //DateTimeOffset endTime = DateBuilder.NextGivenSecondDate(DateTime.Now.AddYears(2), 3);

            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                //.StartAt(startTime).EndAt(endTime)
                .WithCronSchedule(cronExpression)
                .Build();

            scheduler.ScheduleJob(job, trigger);

            scheduler.Start();

            //Thread.Sleep(TimeSpan.FromDays(2));
            //scheduler.Shutdown();
        }
    }

    #region task execution example
    //public class MyJob : IJob
    //{
    //    public void Execute(IJobExecutionContext context)
    //    {
    //        Console.WriteLine("executed..." + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
    //    }
    //} 
    #endregion
}

The general process is as follows:
Instantiate a scheduling factory object through ISchedulerFactory, and instantiate a scheduler scheduling object using the factory,

Then instantiate a task object job, that is, the object that defines the task content. You need to pass in a class that implements the IJob interface. Here I use generics,

Next, you need an object that can trigger a task. There are two kinds,

One is ITrigger, which is used to specify the time interval. After the plan starts, the execution task will be triggered according to the time value of the interval;

The other is ICronTrigger, which is the execution time through Cron expression specification. After the plan starts, if the time meets the specified time, the task will be triggered.

Finally, both the job and trigger are passed into the schedule scheduler, and the schedule starts.

 

The task execution example at the bottom is an example,

The IJob interface and the Execute method must be implemented.

 

If I need to call the data outside the class in the Execute method, I define the static class method in the project for MyJob to call.

 

Program start plan code:

string cronExpression = "0 0 9,16 * * ? "; = > this means that the task is performed at 9:00 and 16:00 every day
QuartzHelper.ExecuteByCron<MyJob>(cronExpression); = > this is a call to the Cron plan method

 

Let's briefly talk about the Cron expression,

"0 0 9,16 * * ? ",

Order from left to right

0: seconds

0: minute

9,16: hours, comma separated

 

If you need a more detailed description, you can baidu.

 
Classification:   C#

Posted by fahim_junoon on Tue, 30 Nov 2021 17:17:07 -0800