当前位置:网站首页>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 triggerASP.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 :## 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
边栏推荐
- Research on data registration and synchronous data flow of soul gateway
- Lakehouse: a new open platform for unified data warehouse and advanced analysis
- Normalization and standardization of feature preprocessing
- Lakehouse: 统一数据仓库和高级分析的新一代开放平台
- 特征预处理之归一化&标准化
- Lakehouse: a new open platform for unified data warehouse and advanced analysis
- Normalization and standardization of feature preprocessing
- 9.软件包管理
- 9. Software package management
- 程序员如何写一份合格的简历?(附简历模版)
猜你喜欢
-
【Soul源码阅读-06】数据同步之websocket
-
How do programmers write a qualified resume? (attach resume template)
-
Websocket for data synchronization
-
【Soul源码阅读-09】数据同步之nacos
-
Nacos for data synchronization
-
一種獲取context中keys和values的高效方法 | golang
-
如何在 Blazor WebAssembly中 使用 功能開關
-
An efficient method to get keys and values in context
-
深入理解原子操作的本質
-
How to use function switch in blazor webassembly
随机推荐
- 日常分享:關於時間複雜度和空間複雜度的一些優化心得分享(C#)
- Podinfo,迷你的 Go 微服務模板
- Deep understanding of the nature of atomic operations
- Daily sharing: some optimization experience sharing about time complexity and space complexity (c)
- Podinfo, mini go microservice template
- 聊聊cortex的tenant
- Talking about tenant of cortex
- 傲视Kubernetes(五):注解和命名空间
- Kubernetes (V): annotation and namespace
- maxwell电机转矩扫描与使用MTPA策略绘制效率map图
- Maxwell motor torque scanning and drawing efficiency map using MTPA strategy
- QT串口助手(三):数据接收
- QT serial assistant (3): data receiving
- QT串口助手(三):数据接收
- QT serial assistant (3): data receiving
- 技术基础 | Apache Cassandra 4.0基准测试
- 技术基础 | Apache Cassandra 4.0基准测试
- Technical foundation Apache Cassandra 4.0 benchmark
- Technical foundation Apache Cassandra 4.0 benchmark
- 草稿
- draft
- 关于数据库中主键自增长问题:Error creating bean with name 'entityManagerFactory' defined in class path
- Error creating bean with name 'entitymanagerfactory' defined in class path
- 面试官角度看应聘:问题到底出在哪?(下)
- 自动化 Web 性能优化分析方案
- 面试官角度看应聘:问题到底出在哪?(上)
- Interviewer's perspective on Application: what's the problem? (2)
- Automated web performance optimization analysis scheme
- Interviewer's perspective on Application: what's the problem? (1)
- [CPP] STL 簡介
- 技術基礎 | Apache Cassandra 4.0基準測試
- QT串列埠助手(三):資料接收
- Introduction to [CPP] STL
- 程式設計師如何寫一份合格的簡歷?(附簡歷模版)
- Lakehouse: 統一資料倉庫和高階分析的新一代開放平臺
- 特徵預處理之歸一化&標準化
- 在.NET Core 中使用Quartz.NET
- Technical foundation Apache Cassandra 4.0 benchmark
- QT serial port assistant (3): data receiving
- 對“微信十年產品思考”的思考