Quartz NetCore定时器任务应用之基于Quartz.Extension.Hosting

上一篇主要介绍基于Quartz原生类库开发netcore定时器任务,有关Quartz的基本概念这里也不再累述了,接下来主要介绍基于Quartz.Extension.Hosting扩展类库快速开发。

1、通过Manage NuGet Pakage / Pakage Manage Console安装Quartz及Quartz.Extensions.Hosting,当前版本如下:

2、首先定义2个定时器任务ServiceJobA,ServiceJobB分别继承自IJob接口,实现Execute方法

using Quartz;

namespace API.Quartz.Jobs;

[DisallowConcurrentExecution]
public class ServiceJobA : IJob
{
    private readonly ILogger<ServiceJobA> _logger;

    public ServiceJobA(ILogger<ServiceJobA> logger)
    {
        _logger = logger;
    }

    public Task Execute(IJobExecutionContext context)
    {
        Task.Run(() =>
        {
            _logger.LogInformation($"DateTime.Now: {DateTime.Now.ToLongTimeString()}, The service job A has been excuted.");
        });
        return Task.CompletedTask;
    }
}
ServiceJobA
using Quartz;

namespace API.Quartz.Jobs;

[DisallowConcurrentExecution]
public class ServiceJobB : IJob
{
    private readonly ILogger<ServiceJobB> _logger;

    public ServiceJobB(ILogger<ServiceJobB> logger)
    {
        _logger = logger;
    }

    public Task Execute(IJobExecutionContext context)
    {
        Task.Run(() =>
        {
            _logger.LogInformation($"DateTime.Now: {DateTime.Now.ToLongTimeString()}, The service job B has been excuted.");
        });
        return Task.CompletedTask;
    }
}
ServiceJobB

3、定义IServiceCollectionQuartzConfigurator的扩展方法,配置IJob及ITrigger,这里通过Configuration读取每个IJob 调度周期

using Quartz;

namespace API.Quartz.Extensisons;

public static class QuartzConfigureExtenstion
{
    public static void AddJobTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config)
        where T : IJob
    {
        var cronExpression = config[$"Quartz:{typeof(T).Name}"];
        if (string.IsNullOrEmpty(cronExpression))
            throw new ArgumentNullException("The service job schedule is null or empty.");
        var jobKey = new JobKey(typeof(T).Name);
        quartz.AddJob<T>(c => c.WithIdentity(jobKey));
        quartz.AddTrigger(c => c.ForJob(jobKey).WithIdentity($"{typeof(T).Name}_trigger").WithCronSchedule(cronExpression));
    }
}
IServiceCollectionQuartzConfigurator

4、利用Quartz.Extension.Hosting提供的AddQuartz及AddQuartzHostedService完成IOC注入

builder.Services.AddQuartz(config =>
{
    config.UseMicrosoftDependencyInjectionJobFactory();
    config.AddJobTrigger<API.Quartz.Jobs.ServiceJobA>(builder.Configuration);
    config.AddJobTrigger<API.Quartz.Jobs.ServiceJobB>(builder.Configuration);
});
builder.Services.AddQuartzHostedService(options =>
{
    options.AwaitApplicationStarted = true;
    options.WaitForJobsToComplete = true;
});
IOC

5、appsettings.json配置

  "Quartz": {
    "ServiceJobA": "0/5 * * * * ?",
    "ServiceJobB": "0/30 * * * * ?"
  }

启动程序,效果如下:

 JobServiceA每5s执行一次,JobServiceB每30s执行一次。

利用Quartz的扩展类库开发netcore 定时器作业调用更加简洁方便,更多应用还需继续学习!!!

posted @ 2023-03-04 09:34  云霄宇霁  阅读(298)  评论(0编辑  收藏  举报