欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

.net?6?配置QuartZ定時(shí)任務(wù)的過程

 更新時(shí)間:2024年04月19日 11:51:56   作者:菜鳥Coco  
這篇文章主要介紹了.net?6?配置QuartZ定時(shí)任務(wù)的過程,在VS2022中,通過Nuget包管理器安裝Quartz?3.8.1 ,這是.net 6 依賴的最高版本,在此記錄學(xué)習(xí)一下,需要的朋友可以參考下

項(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ù)

KSO - 在.NET6中項(xiàng)目級(jí)使用配置Quartz.NET定時(shí)任務(wù),并使用IHostedService實(shí)現(xiàn)項(xiàng)目啟動(dòng)自動(dòng)加載任務(wù),常用的Corn表達(dá)式_net6 webapi 在配置中引入注入quartz

到此這篇關(guān)于.net 6 配置QuartZ定時(shí)任務(wù)的文章就介紹到這了,更多相關(guān).net 6 QuartZ定時(shí)任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論