This is my first day to participate in the Novembermore Challenge

The background,

For example, you need to update or synchronize some data in the database in a certain month in a certain year, or execute a part of the code to call the interface every once in a while, but you don’t want to manually execute it

For this type of business, you can use “scheduled call task”. There are many scheduled task frameworks on the market, and you can even use timer to make a simple version of the task scheduler in conjunction with Windows services. Here we study Quartz, because It is a powerful, open source, lightweight task scheduling framework that supports Cron-L Ike expressions have some other nice features.

Second, the Quartz

1. Basic concepts
Scheduler Trigger Job
Scheduler, a stand-alone container for Quartz at work Trigger, which defines the time rules for scheduling tasks The container that invokes the action to be performed by the task
2. Preliminary use

1.Nuget introduces the QuartZ assembly

2. Create a Scheduler task scheduling container

3. Specify Job and trigger

4. Put policies and tasks into the Scheduler and start them

public class QuartzManager { public async static void Init() { StdSchedulerFactory factory = new StdSchedulerFactory(); // create a Scheduler task Scheduler container IScheduler = await factory.getscheduler (); IJobDetail sendEmailJob = jobBuilder.create <SendMailJob>().WithIdentity("sendEmailJob", "SendEmailJobGrop ").withDescription (" timed mail ").build (); ITrigger sendEmailTrigger = triggerBuilder.create ().withidentity ("sendEmailTrigger", "sendEmailJobGrop" .WithDescription("QuartZ") .WithCronSchedule("3/5 * * * * ?" ) .Build(); Scheduler await scheduler.ScheduleJob(sendEmailJob, sendEmailTrigger); // Execute task await scheduler.start (); }} / / add features that will not overlap task execution [DisallowConcurrentExecution] public class SendMailJob: IJob {//Job public Async Task Execute(IJobExecutionContext Context) {await task.run (() => {//doSomthing Console.WriteLine($" Start sending mail {datetime.now}"); }); }}Copy the code

3. Pass parameters

The Quartz parameter is used when you want to execute a Job with parameters and do some logical processing based on those parameters. There are several ways to transmit the reference in Quartz

1. The job involved

2. The Trigger to participate

1. Job and Trigger parameters are transmitted

Add the parameter using jobDatamap. Add, which is obtained using jobDatamap. GetString of the context inside the job

IJobDetail sendEmailJob = JobBuilder.Create<SendMailJob>().Build(); / / to the Job and a parameter sendEmailJob JobDataMap. Add (" params ", "Job test pass participation"); ITrigger trigger = TriggerBuilder.Create().Build(); Jobdatamap. Add("params", "trigger test parameter "); Public async Task Execute(IJobExecutionContext Context) {await task.run (() => {// Get job parameters string paramJob =  context.JobDetail.JobDataMap.GetString("params"); / / get the Trigger preach and string paramTrigger = context. The Trigger. The JobDataMap. Get string (" params "); //doSomthing console. WriteLine($" Start sending mail {datetime.now}"); }); }Copy the code

Register the listener in scheduler

Listeners are objects created to perform actions on events that occur in the scheduler. There are three main types of listeners

1. Scheduling listener ISchedulerListener Is used to monitor the scheduling process.

2. TriggerListener ITriggerListener is used to receive trigger related event listener.

3. Job listener IJobListener is used to receive listening for events related to the Job running life cycle.

1. Implement listeners

Take job listeners as an example, since triggering is implemented in the same way as scheduling listeners.

1. Custom job listeners need to inherit the IJobListener interface and implement methods.

2. Add a custom listener in the listener management of the scheduler.

Public class CustomJobListener: IJobListener {public string Name => "CustomJobListener"; } / / added to the monitor management scheduler ListenerManager. AddJobListener (new CustomJobListener ());Copy the code

5. Visual management interface

Visual tool used to view information about the current running Job.

1. Create a New Web project or console project.

2. Nuget introduces the Quartz and CrystalQuartz.Remote packages in web projects

3. Configure StdSchedulerFactory information in Job scheduling to specify the listening port

var properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "Test Monitor System"; / / set the thread pool properties [" quartz. The threadPool. Type "] = "quartz. Simpl. SimpleThreadPool, quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; / / remote output configuration properties [. Quartz scheduler. The exporter. "type"] = "quartz. Simpl. RemotingSchedulerExporter, quartz"; properties["quartz.scheduler.exporter.port"] = "8081"; properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler"; properties["quartz.scheduler.exporter.channelType"] = "tcp"; var schedulerFactory = new StdSchedulerFactory(properties); IScheduler _scheduler = await schedulerFactory.GetScheduler();Copy the code

4. On the Web monitoring terminal, access crystalQuartzPanel. axd under the unified port number.

6. Configuration File Configuration tasks

In addition to defining the various schedules and triggers for the task in your code, you can also create a Job task using an XML configuration file

1. Prepare a configuration file and configure Job+trigger information. Make sure that the file property is always copied.

<? The XML version = "1.0" encoding = "utf-8"? > <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" version = "2.0" > < processing - directives > <overwrite-existing-data>true</overwrite-existing-data> </processing-directives> <schedule> <job> <name>sendEmailJob</name> <group>Test Mail Job</group> <description>This is Test Mail Job</description> <! -- This is the class where the Job is located, And the assembly - > < job - type > DispatcherProject. Job. SendMailJob, DispatcherProject < / job - type > < durable > true < / durable > <recover>false</recover> </job> <trigger> <cron> <name>sendEmailTrigger</name> <group>sendEmailJobGrop</group> <job-name>sendEmailJob</job-name> <job-group>Test Mail Job</job-group> <cron-expression>5/3 * * * * ? </cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>Copy the code

2. Read the configuration file to obtain the information and generate the corresponding Job and Trigger

XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); / / read the configuration file await processor. ProcessFileAndScheduleJobs (~ / config/quartz. XML, the scheduler); // Start the scheduler task await scheduler.start ();Copy the code