.net?6?配置QuartZ定時(shí)任務(wù)的過程
項(xiàng)目中需要用到QuartZ執(zhí)行定時(shí)任務(wù),在此記錄一下學(xué)習(xí)過程。
Quartz安裝
在VS2022中,通過Nuget包管理器安裝Quartz 3.8.1 ,這是.net 6 依賴的最高版本。
創(chuàng)建定時(shí)器任務(wù)
1、創(chuàng)建QuartzConfigurator
新建QuartzConfiguratorExtensions類,用于注冊(cè)觸發(fā)器和任務(wù),代碼如下:
/// <summary> /// 添加任務(wù)和觸發(fā)器 /// </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 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<T>(opts => opts.WithIdentity(jobKey)); quartz.AddTrigger(opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration } /// <summary> /// 添加任務(wù)和觸發(fā)器(帶參數(shù)傳遞) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="quartz"></param> /// <param name="config"></param> /// <param name="keyValuePairs">需要傳遞的參數(shù)</param> /// <param name="IsTriggerJobDataMap">默認(rèn)通過 工作描述時(shí)傳遞參數(shù)</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 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); if (keyValuePairs != null && isJobDetailJobDataMap) { switch (isJobDetailJobDataMap) { case true: quartz.AddJob<T>(opts => opts .WithIdentity(jobKey) .UsingJobData(new JobDataMap(keyValuePairs))); quartz.AddTrigger(opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration break; case false: quartz.AddJob<T>(opts => opts .WithIdentity(jobKey)); quartz.AddTrigger(opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule) .UsingJobData(new JobDataMap(keyValuePairs))); // use the schedule from configuration break; } } else { quartz.AddJob<T>(opts => opts .WithIdentity(jobKey)); quartz.AddTrigger(opts => opts .ForJob(jobKey) .WithIdentity(jobName + "-trigger") .WithCronSchedule(cronSchedule)); // use the schedule from configuration } }
2、在Program.cs 中注入服務(wù)
builder.Services.AddQuartz(q => { 創(chuàng)建計(jì)劃單元(時(shí)間軸,載體) //StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); //var scheduler = await schedulerFactory.GetScheduler(); //await scheduler.Start(); q.UseMicrosoftDependencyInjectionJobFactory(); // Register the job, loading the schedule from configuration q.AddJobAndTrigger<FromKingdeeWorkerJob>(builder.Configuration); }); builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
3、創(chuàng)建工作單元WorkerJob
新建類TestWorkerJob,并繼承IJob,代碼如下:
[PersistJobDataAfterExecution]//在執(zhí)行完成后,保留JobDataMap數(shù)據(jù) [DisallowConcurrentExecution]//不允許并發(fā)執(zhí)行,即必須等待上次完成后才能執(zhí)行下一次 public class TestWorkerJob : IJob { private readonly ILogger<TesteWorkerJob> _logger; public TestWorkerJob(ILogger<TestWorkerJob> logger) { _logger = logger; } public Task Execute(IJobExecutionContext context) { _logger.LogInformation(DateTime.Now +" --- Hello world!"); Task.Delay(50000); Thread.Sleep(10000); return Task.CompletedTask; } }
假如我們的定時(shí)任務(wù),執(zhí)行一次需要耗時(shí)比較久,而且后一次執(zhí)行需要等待前一次完成,并且需要前一次執(zhí)行的結(jié)果作為參考,那么就需要設(shè)置任務(wù)的任性。因?yàn)槟J(rèn)情況下,工作單元在每一次運(yùn)行都是一個(gè)新的實(shí)例,相互之間獨(dú)立運(yùn)行,互不干擾。所以如果需要存在一定的關(guān)聯(lián),就要設(shè)置任務(wù)的特性,主要有兩個(gè),如下所示:
[PersistJobDataAfterExecution]//在執(zhí)行完成后,保留JobDataMap數(shù)據(jù)
[DisallowConcurrentExecution]//不允許并發(fā)執(zhí)行,即必須等待上次完成后才能執(zhí)行下一次
以上兩個(gè)特性,只需要標(biāo)記在任務(wù)對(duì)應(yīng)的類上即可。
4、appsettings.json配置
在appsettings.json文件中添加一項(xiàng)Quartz,子項(xiàng)的必須與WorkerJob的名字保持一致,value是Cron表達(dá)式
{ "Quartz": { "FromKingdeeWorkerJob": "0/5 * * * * ?" } }
然后,啟動(dòng)項(xiàng)目,就可以看到任務(wù)可以正常運(yùn)行啦。
最后
最后附上學(xué)習(xí)鏈接,
.NET6+Quartz實(shí)現(xiàn)定時(shí)任務(wù)
到此這篇關(guān)于.net 6 配置QuartZ定時(shí)任務(wù)的文章就介紹到這了,更多相關(guān).net 6 QuartZ定時(shí)任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
.Net語(yǔ)言Smobiler開發(fā)之如何仿微信朋友圈的消息樣式
這篇文章主要介紹了.Net語(yǔ)言Smobiler開發(fā)平臺(tái)如何仿微信朋友圈的消息樣式?本文為大家揭曉答案2016-09-09CheckBox為CheckBoxList實(shí)現(xiàn)全選或全取消選擇(js代碼實(shí)現(xiàn))
在管理商品后臺(tái)是,由于CheckBoxList的選擇太多,用戶需要一個(gè)全選或全取消的功能,這樣操作起來會(huì)提高效率同時(shí)可以減少誤點(diǎn)等,本文將教大家如何實(shí)現(xiàn),有需要的朋友可以參考下,望本文對(duì)你有所幫助2013-01-01詳解ASP.NET Core3.0 配置的Options模式
這篇文章主要介紹了詳解ASP.NET Core3.0 配置的Options模式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08ASP.NET實(shí)現(xiàn)QQ、微信、新浪微博OAuth2.0授權(quán)登錄
本文主要介紹了QQ、微信、新浪微博OAuth2.0授權(quán)登錄的示例,主要就是GET、POST遠(yuǎn)程接口,返回相應(yīng)的數(shù)據(jù),這里列出相關(guān)的代碼,供大家參考。2016-03-03asp.net中使用DatagridView的增刪改方法具體實(shí)現(xiàn)
asp.net中使用DatagridView的增刪改方法具體實(shí)現(xiàn),需要的朋友可以參考一下2013-06-06