QuartZ needs to be used in the project to perform timing tasks, and here is the learning process.
Quartz installation
In VS2022, Quartz 3.8.1 is installed through the Nuget package manager, which is the highest version that .net 6 depends on.
Create a timer task
1. Create QuartzConfigurator
Create a new QuartzConfiguratorExtensions class to register triggers and tasks. The code is as follows:
/// <summary> /// Add tasks and triggers /// </summary> /// <typeparam name="T"></typeparam> /// <param name="quartz"></param> /// <param name="config"></param> /// <exception cref="Exception"></exception> public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config) where T : IJob { // Use the name of the IJob as the key string jobName = typeof(T).Name; // Try and load the schedule from configuration var configKey = $"Quartz:{jobName}"; var cronSchedule = config[configKey]; // Some minor validation if ((cronSchedule)) { throw new Exception($"No Cron schedule found for job in configuration at {configKey}"); } // register the job as before var jobKey = new JobKey(jobName); <T>(opts => (jobKey)); (opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration } /// <summary> /// Add tasks and triggers (with parameters passed) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="quartz"></param> /// <param name="config"></param> /// <param name="keyValuePairs">parameters that need to be passed</param> /// <param name="IsTriggerJobDataMap">Pass parameters by default when passing the job description</param> /// <exception cref="Exception"></exception> public static void AddJobAndTriggerWithParameter<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config, IDictionary<string, object>? keyValuePairs = null, bool isJobDetailJobDataMap = true) where T : IJob { // Use the name of the IJob as the key string jobName = typeof(T).Name; // Try and load the schedule from configuration var configKey = $"Quartz:{jobName}"; var cronSchedule = config[configKey]; // Some minor validation if ((cronSchedule)) { throw new Exception($"No Cron schedule found for job in configuration at {configKey}"); } // register the job as before var jobKey = new JobKey(jobName); if (keyValuePairs != null && isJobDetailJobDataMap) { switch (isJobDetailJobDataMap) { case true: <T>(opts => opts .WithIdentity(jobKey) .UsingJobData(new JobDataMap(keyValuePairs))); (opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration break; case false: <T>(opts => opts .WithIdentity(jobKey)); (opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule) .UsingJobData(new JobDataMap(keyValuePairs))); // use the schedule from configuration break; } } else { <T>(opts => opts .WithIdentity(jobKey)); (opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration } }
2. Inject services in
(q => { Create a planning unit(Timeline,Vector) //StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); //var scheduler = await (); //await (); (); // Register the job, loading the schedule from configuration <FromKingdeeWorkerJob>(); }); (q => = true);
3. Create a work unit WorkerJob
Create a new class TestWorkerJob and inherit IJob, the code is as follows:
[PersistJobDataAfterExecution]//After the execution, retain the JobDataMap data [DisallowConcurrentExecution]//Concurrent execution is not allowed, that is, you must wait until the last completion before the next execution will be executed. public class TestWorkerJob : IJob { private readonly ILogger<TesteWorkerJob> _logger; public TestWorkerJob(ILogger<TestWorkerJob> logger) { _logger = logger; } public Task Execute(IJobExecutionContext context) { _logger.LogInformation( +" --- Hello world!"); (50000); (10000); return ; } }
If our timed task takes a long time to execute, and the next execution requires waiting for the previous completion, and the result of the previous execution is required as a reference, then the task willfulness needs to be set. Because by default, the work unit is a new instance every time it runs, running independently of each other and not interfering with each other. Therefore, if there is a certain relationship, you need to set the characteristics of the task. There are two main features, as shown below:
[PersistJobDataAfterExecution]//After the execution is completed, retain the JobDataMap data
[DisallowConcurrentExecution]//Concurrent execution is not allowed, that is, you must wait until the last completion before the next execution is executed.
The above two features only need to be marked on the corresponding class of the task.
4. Configuration
Add a Quartz to the file. The child must be consistent with the WorkerJob name, and the value isCron expressions
{ "Quartz": { "FromKingdeeWorkerJob": "0/5 * * * * ?" } }
Then, start the project and you can see that the task can run normally.
at last
Finally, the learning link is attached.
.NET6+Quartz implements timing tasks
KSO - Use configuration timing tasks at the project level in .NET6, and use IHostedService to implement project startup automatic loading tasks. Common Corn expressions_net6 webapi introduces injection quartz in configuration
This is the end of this article about .net 6 configuring QuartZ timing tasks. For more related .net 6 quartz timing tasks, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!