当前位置:网站首页>Using in. Net core Quartz.NET

Using in. Net core Quartz.NET

2021-01-24 02:13:44 itread01

Quartz.NET It is a fully functional open source job scheduling system , For the smallest applications to large enterprise systems .Quartz.NET There are three main concepts :- job: Perform background tasks - trigger: Triggers that control the execution of background tasks .- scheduler: To coordinate job and trigger![](https://blog-1259586045.cos.ap-shanghai.myqcloud.com/clipboard_20210123_095408.png)ASP.NET Core Execute... Through hosted services “ Background tasks ” With good support , The hosting service is in ASP.NET Core Start when the application starts , And runs in the background during the lifetime of the application ,Quartz.NET edition 3.2.0 Through Quartz.Extensions.Hosting The package introduces direct support for the pattern ,Quartz.Extensions.Hosting Can be associated with ASP.NET Core Applications together , It can also be used with “ Universal host ” To be used together with other workflow services . Although .NET Core Can be established “ Timing ” Background services ( for example , Every time 10 One task per minute ), but Quartz.NET Provides a more powerful solution , By using Cron The expression , You can make sure that the task is at a specific time ( for example , In the morning 2:30) Execute , Or only for a certain number of days , Or any combination of these times .Quartz.NET It also allows you to cluster multiple instances of your application , So that only one instance can be executed at any time .## Install Quartz.NETQuartz.NET It's a .NET Standard 2.0 NuGet Software package , So most projects are supported , You can execute the installation command ,`dotnet add package Quartz.Extensions.Hosting`, Or in NNuget Visual installation , If you view the .csproj, It should be like this below :```csharp net5.0 dotnet-QuartzWorkerService-9D4BFFBE-BE06-4490-AE8B-8AF1466778FD ``` After the installation is complete , This package will be installed automatically Quartz.NET package , Next , We need to register in our application Quartz Services and Quartz .## newly added Quartz.NET hosted service modify Program.cs, Registration services ```csharppublic class Program{ public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { // Add the required Quartz.NET services services.AddQuartz(q => { // Use a Scoped container to create jobs. I'll touch on this later q.UseMicrosoftDependencyInjectionScopedJobFactory(); }); // Add the Quartz.NET hosted service services.AddQuartzHostedService( q => q.WaitForJobsToComplete = true); // other config });}```UseMicrosoftDependencyInjectionScopedJobFactory(), This place tells Quartz.NET Sign up for one IJobFactory, And then from DI Container Job, It can also be used Scoped Type of service .WaitForJobsToComplete(): When the program is closed , This setting ensures that Quartz.NET Wait before you exit Job Normal end . If you run your application now , You will see Quartz Service start , And there will be a lot of log output to the console :```csharpinfo: Quartz.Core.SchedulerSignalerImpl[0] Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImplinfo: Quartz.Core.QuartzScheduler[0] Quartz Scheduler v.3.2.3.0 created.info: Quartz.Core.QuartzScheduler[0] JobFactory set to: Quartz.Simpl.MicrosoftDependencyInjectionJobFactoryinfo: Quartz.Simpl.RAMJobStore[0] RAMJobStore initialized.info: Quartz.Core.QuartzScheduler[0] Scheduler meta-data: Quartz Scheduler (v3.2.3.0) 'QuartzScheduler' with instanceId 'NON_CLUSTERED' Scheduler class: 'Quartz.Core.QuartzScheduler' - running locally. NOT STARTED. Currently in standby mode. Number of jobs executed: 0 Using thread pool 'Quartz.Simpl.DefaultThreadPool' - with 10 threads. Using job-store 'Quartz.Simpl.RAMJobStore' - which does not support persistence. and is not clustered.info: Quartz.Impl.StdSchedulerFactory[0] Quartz scheduler 'QuartzScheduler' initializedinfo: Quartz.Impl.StdSchedulerFactory[0] Quartz scheduler version: 3.2.3.0info: Quartz.Core.QuartzScheduler[0] Scheduler QuartzScheduler_$_NON_CLUSTERED started.info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down....``` Now , You have Quartz Run as a managed service in your application , But there is no new one to be executed yet Job.## Build a IJob This is a place where I build a simple service , And I can get services from constructors .```csharpusing Microsoft.Extensions.Logging;using Quartz;using System.Threading.Tasks;[DisallowConcurrentExecution]public class HelloWorldJob : IJob{ private readonly ILogger _logger; public HelloWorldJob(ILogger logger) { _logger = logger; } public Task Execute(IJobExecutionContext context) { _logger.LogInformation("Hello world!"); return Task.CompletedTask; }}``` I still use [DisallowConcurrentExecution] characteristic , prevent Quartz.NET Try running the same job at the same time .### Set Job This place usually uses Cron The expression , To set job The execution time of .```csharppublic static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddQuartz(q => { q.UseMicrosoftDependencyInjectionScopedJobFactory(); // Create a "key" for the job var jobKey = new JobKey("HelloWorldJob"); // Register the job with the DI container q.AddJob (opts => opts.WithIdentity(jobKey)); // Create a trigger for the job q.AddTrigger(opts => opts .ForJob(jobKey) // link to the HelloWorldJob .WithIdentity("HelloWorldJob-trigger") // give the trigger a unique name .WithCronSchedule("0/5 * * * * ?")); // run every 5 seconds }); services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true); // ... });``` Now run the application , You will see the same startup message as before , And then every 5 You'll see in a second HelloWorldJob Information written to the console :![](https://blog-1259586045.cos.ap-shanghai.myqcloud.com/clipboard_20210123_094338.png)## Extract the configuration to appsettings.json General , We're not going to put cron Representations are written dead in code , It's usually set at appsettings.json in ```csharp{ "Quartz": { "HelloWorldJob": "0/5 * * * * ?" }}``` For a simpler registration service , I made a simple package for this place , It's also more flexible .```csharppublic static class ServiceCollectionQuartzConfiguratorExtensions{ public static void AddJobAndTrigger ( this IServiceCollectionQuartzConfigurator quartz, IConfiguration config) where T : IJob { // Use the name of the IJob as the appsettings.json 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 (string.IsNullOrEmpty(cronSchedule)) { throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}"); } // register the job as before var jobKey = new JobKey(jobName); quartz.AddJob (opts => opts.WithIdentity(jobKey)); quartz.AddTrigger(opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration }}``` Then modify Program.cs, Then use the extension suite method : ```csharppublic class Program{ public static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddQuartz(q => { q.UseMicrosoftDependencyInjectionScopedJobFactory(); // Register the job, loading the schedule from configuration q.AddJobAndTrigger (hostContext.Configuration); }); services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true); });}``` Running the application again will provide the same output :Job Every time 5 Enter information once a second .> Original author : andrewlock> Link to the original text : [https://andrewlock.net/using-quartz-net-with-asp-net-core-and-worker-services/]("https://andrewlock.net/using-quartz-net-with-asp-net-core-and-worker-services/") ### Finally, welcome to scan the code and pay attention to our public account 【 Global technology highlights 】, Focus on translation and open source project sharing of foreign excellent blogs , You can also add QQ Group 897216102

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/01/20210124021047869q.html

随机推荐