Preface:
Have you ever needed an application to perform a task? For example, there is a requirement to perform some operations at zero point every day. How should it be operated?
At this point, if you and your team are programming in. NET, consider using the Quartz.NET scheduler. Allow developers to schedule tasks based on date intervals. It is very suitable for normal work, such as periodic polling database synchronization, periodic email notification, periodic data processing, etc.
Quartz is an open source job scheduling framework, which is ported every other time by OpenSymphony's Quartz API. It is written on C# and can be used in winform, asp.net and asp.net core applications. It provides great flexibility and is a more powerful, manageable and cluster deployment job scheduling framework.
So sometimes a project needs to perform one or more different jobs at different times, and you can use it to perform tasks that create simple or complex scheduling.
Map:
Characteristic:
1: Support cluster, job grouping, job remote management.
2: Customize fine time flip-flop, easy to use, separation of operation and trigger.
3: database support, can host Windows services, WebSite, winform and so on.
Concept:
Scheduler Job Scheduler
All schedulers should be created by scheduler Factory
//Establish scheduler Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
IJob. Job interface, inherits and implements Execute, and writes specific job logic for execution.
By implementing the IJob interface, your. NET components can be easily executed by scheduler
public class ConsoleJob : IJob { public Task Execute(IJobExecutionContext context) { return Console.Out.WriteLineAsync($"Execution of jobs"); } }
JobBuilder generates a detailed job information (JobDetail) based on the settings.
JobBuilder is a builder model, chain building. Construct a JobBuilder instance through a static method, and then call the class method Build() to create an implementation of IJobDetail.
public static JobBuilder Create(Type jobType) { JobBuilder b = new JobBuilder(); b.OfType(jobType); return b; }
Trigger Builder produces the corresponding Trigger according to the rules, and the trigger can plan and execute tasks.
Construct a TriggerBuilder instance through a static method, and then call the class method Build() to create an ITrigger implementation.
public static TriggerBuilder Create() { return new TriggerBuilder(); }
Setting the start and end times of triggers according to tasks
/// <summary> /// start time /// </summary> /// <param name="startTimeUtc"></param> /// <returns></returns> public TriggerBuilder StartAt(DateTimeOffset startTimeUtc) { startTime = startTimeUtc; return this; } /// <summary> /// Ending time /// </summary> /// <param name="endTimeUtc"></param> /// <returns></returns> public TriggerBuilder EndAt(DateTimeOffset? endTimeUtc) { endTime = endTimeUtc; return this; }
Steps:
1. Create an ISchedulerFactory and get Scheduler
2. Start Scheduler
3. Create job tasks
4. Create trigger triggers
5. Use triggers to plan tasks
Start:
Be careful:
After you create a new Quartz project, you need to install the following package:
You can install it by console command
Install-Package Quartz
You can also choose the installation version in the following way
First, create a scheduler reference:
ISchedulerFactory schedFact = new StdSchedulerFactory(); IScheduler sched = await schedFact.GetScheduler();
2. Start scheduler:
await sched.Start();
Implementing IJob:
ConsoleJob.cs implements IJob and writes the business logic to be processed in Execute method. The system will process it regularly according to the configuration of Quartz.
/// <summary> /// Realization IJob,Execute Write the business logic to be processed in the method /// </summary> public class ConsoleJob : IJob { public Task Execute(IJobExecutionContext context) { return Console.Out.WriteLineAsync($"ConsoleJob Execution at the current time{DateTime.Now}--Last execution time:{DateTime.Now.AddSeconds(-5)}"); } }
4. Create trigger: (Establish a trigger at a certain time point and execute it every 5 seconds)
ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") //Flip-flop group .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build();
5. Triggers perform tasks:
await sched.ScheduleJob(job, trigger);
Integrate several steps into the following code:
/// <summary> /// The Use Process of Task Scheduling /// </summary> /// <returns></returns> public async static Task Run() { // 1.Establish scheduler Citation ISchedulerFactory schedFact = new StdSchedulerFactory(); IScheduler sched = await schedFact.GetScheduler(); //2.start-up scheduler await sched.Start(); // 3.Establish job IJobDetail job = JobBuilder.Create<ConsoleJob>() .WithIdentity("job1", "group1") .Build(); // 4.Establish trigger (Establish trigger Trigger) ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") //Flip-flop group .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build(); // 5.Use trigger Planning and executing tasks job (Use triggers to plan tasks await sched.ScheduleJob(job, trigger); }
Function:
The effect of executing once every 5 seconds:
Additional:
The quartz version used here is 3.x, and the entire version has been heavily modified relative to version 2.0, officially supporting. NET Core and async/await.
Quote Zhang team Contents of the article:
Summary:
1. In fact, in practical projects, the above methods can be encapsulated and processed to form different tasks, especially when dealing with multi-tasks, different trigger s can be invoked in different job s, which will continue to improve the development in the future.
2. Quatz has many more uses, you can refer to: Quartz.Net Official Document And Quartz.Net Open Source Address