Timing scheduling can be understood as the regular execution of a method or logic code, and Timer can also realize similar functions. Quartz is a framework for starting scheduled tasks, which can be called directly after the project is referenced.
preparation:
Project installation Quartz
Code implementation:
1. Declare scheduler (job scheduling pool)
2. Statement JobDetail
3. Statement Trigger
4. Add JobDetail and Trigger to the job scheduling pool
Here are the detailed steps:
The project refers to Quartz and is installed using NuGet package manager. The Quartz I installed is version 3.0.7 (different versions have different api calling methods, and there is a big difference between 2.x and 3.x) Net framework version requires at least 4.5.2.
Code implementation part:
1.Scheduler job scheduler
StdSchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = await factory.GetScheduler(); await scheduler.Start();
2.JobBuilder generates a detailed job information (JobDetail) according to the settings.
IJobDetail jobDetail1 = JobBuilder.Create<JobDemo>().WithIdentity("testjob", "group1").WithDescription("I am testjob").Build(); jobDetail1.JobDataMap.Add("name", "Zhang San"); jobDetail1.JobDataMap.Add("age", "20");
3.TriggerBuilder: produce the corresponding Trigger according to the rules
//The program is executed 2 seconds after startup, once every 3 seconds, and always ITrigger trigger = TriggerBuilder.Create().WithIdentity("testtrigger", "group1").StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(2))) .WithCronSchedule("0/3 * * * * ?").WithDescription("I am testjob Trigger for").Build();
4. Join the job scheduling pool
await scheduler.ScheduleJob(jobDetail1, trigger);
The complete code is as follows:
public async static Task Init() { try { Console.WriteLine("initialization scheduler....."); //1.Scheduler job scheduler StdSchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = await factory.GetScheduler(); await scheduler.Start(); //2.JobBuilder generates a detailed job information (JobDetail) according to the settings. IJobDetail jobDetail1 = JobBuilder.Create<JobDemo>().WithIdentity("testjob", "group1").WithDescription("I am testjob").Build(); jobDetail1.JobDataMap.Add("name", "Zhang San"); jobDetail1.JobDataMap.Add("age", "20"); //3.TriggerBuilder produces the corresponding Trigger according to the rules //The program is executed 2 seconds after startup, once every 3 seconds, and always ITrigger trigger = TriggerBuilder.Create().WithIdentity("testtrigger", "group1").StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(2))) .WithCronSchedule("0/3 * * * * ?").WithDescription("I am testjob Trigger for").Build(); //4. Join the job scheduling pool await scheduler.ScheduleJob(jobDetail1, trigger); Console.WriteLine("Job addition complete....."); } catch (Exception) { throw; } }
The custom logic is written in the JobDemo class in step 2. The code is as follows:
//IJob job interface, inherit and implement Execute, and write specific job logic for execution. public class JobDemo : IJob { public async Task Execute(IJobExecutionContext context) { try { await Task.Run(() => { Console.WriteLine(); JobDataMap map = context.JobDetail.JobDataMap; Console.WriteLine(map.Get("name")); Console.WriteLine(map.Get("age")); Console.WriteLine(DateTime.Now.ToString("r")); Console.WriteLine(); }); } catch (Exception) { throw; } } }
The parameter added in the second step of the program is the information in the second step of the program start-up logic. Print every 3 seconds and execute as long as the program does not stop.
As follows:
Supplement and extension of usage:
In the third step, Trigger is created to control the cycle and times of program operation
The Cron expression is used in the above code example. For detailed usage, refer to: https://www.cnblogs.com/sunjie9606/archive/2012/03/15/2397626.html
At the same time, there are tools for generating Cron expressions on the Internet, which can automatically generate expressions according to the selected time: https://cron.qqe2.com/
In addition to Cron expression, there are other ways to control the cycle of program operation, such as Simple mode. The code is as follows:
//The program is executed immediately after startup, once every second, a total of 2 + 1 times ITrigger trigger = TriggerBuilder.Create().WithIdentity("testtrigger", "group1").StartNow() .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).WithRepeatCount(2)).WithDescription("I am testjob Trigger for").Build();
This code can replace the code in the third part of the above example. The logic is to execute the task immediately after the program is started. It is executed every second, twice in total. Plus the first execution, it will be executed three times in total.
StartNow(), execute the job task immediately
WithIntervalInSeconds(1), executed once a second
WithRepeatCount(2), which is repeated twice. Here, you can also use RepeatForever() to indicate that it will be executed forever without limiting the number of executions.
There are many other APIs that can be viewed by yourself. The viewing methods are as follows:
About listening Listener
Quartz's listener is used to get the notification of the event in time when the event concerned in task scheduling occurs. It is similar to email and SMS reminders during task execution. Quartz listeners mainly include SchedulerListener, TriggerListener and JobListener, which respectively represent the listeners corresponding to scheduler, trigger and task.
The three methods are similar. Take TriggerListener as an example to write a class to explain its usage:
MyTriggerListener class:
public class MyTriggerListener : ITriggerListener { public string Name => "MyTriggerListener"; public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default(CancellationToken)) { await Task.Run(() => { Console.WriteLine("job Called on completion"); Console.WriteLine(); }); } public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken)) { await Task.Run(() => { Console.WriteLine("job Called on execution"); }); } public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken)) { await Task.Run(() => { Console.WriteLine("Called when the trigger is missed(Example: when the thread is not enough)"); }); } public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken)) { //After Trigger is triggered, this method is called during job execution. true means veto and will not be executed after the job. await Task.Run(() => { Console.WriteLine("Trigger After triggering, job This method is called during execution."); }); return false; } }
After the custom MyTriggerListener is implemented, you need to add a listener to the specified trigger, as shown in the figure:
Code:
scheduler.ListenerManager.AddTriggerListener(new MyTriggerListener());//Add TriggerListener
After adding, start the project again, and you can see the relevant information printed on the console:
The usage of the other two listeners is similar.
About the listener, you can refer to the following link. Although it is a java version, many things are the same, after all Net Quartz is a change from the Java version.