当我们在web开发中,常常会遇到这么一个需求,在后台执行某一项具体的任务,具体的说就是这些任务必须在后台定时执行。

Quartz.NET 是一个开源的 JAVA 移植版,它有着悠久的历史并且提供了强大的 Cron 表达式,这篇我们就来讨论如何在 ASP.NET Core 中使用 Quartz.NET 去执行一些后台任务。

一:安装 Quartz.NET

要想使用 Quartz.NET,你可以使用 Visual Studio 2019 中的 NuGet package manager 可视化界面进行安装;

二:Quartz.NET 中的Job,triggers 和 Schedulers

1.Quartz.NET 里有三个非常重要的概念:任务,触发器 和 调度器,对应着 Job,Trigger 和 2.Schedulers,Job 表示一个你需要被执行的任务,任务中可以写上你的业务逻辑代码,Job 就是一个实现了 IJob 接口的子类。 Trigger 通常用于指定一个 job 是如何被调度的? 什么意思呢? 比如说:这个job是按天执行? 还是按小时执行?还是按秒执行?值得注意的是因为支持了 Cron 表达式,还能够实现更加超级复杂的调度逻辑。 3.Scheduler 通常按照你预先设置的调度规则将 job 丢给它的任务队列,并按照 trigger 规则轮询然后执行任务。

三:创建Job:

using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Services
{

    [DisallowConcurrentExecution]
    public class NotificationJob : IJob
    {
        private readonly ILogger<NotificationJob> _logger;
        public NotificationJob(ILogger<NotificationJob> logger)
        {
            _logger = logger;
        }
        public Task Execute(IJobExecutionContext context)
        {
            //此处可以写业务逻辑
            _logger.LogInformation("Hello world!"+DateTime.Now);
            return Task.CompletedTask;
        }
    }

}

三:创建 JobMetadata 存储你的 job 元数据:

我准备定义一个 JobMetadata 类去存储和job 相关联的元数据,比如说:job的id,job的name 等等,下面的代码展示了如何定义这么一个类。

public class JobMetadata
    {
        public string JobId { get; set; }
        public Type JobType { get; }
        public string JobName { get; }
        public string CronExpression { get; }
        public JobMetadata(string Id, Type jobType, string jobName,
        string cronExpression)
        {
            JobId = Id;
            JobType = jobType;
            JobName = jobName;
            CronExpression = cronExpression;
        }
    }

三: 创建scheduler:

为了方便实现 开启 和 停止 功能,我准备封装一个 hosting service 类,做法就是从 IHostingService 接口派生出一个 CustomQuartzHostedService 类,完整代码如下:

using Microsoft.Extensions.Hosting;
using Model;
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Services
{
    public class CustomQuartzHostedService : IHostedService
    {
        private readonly ISchedulerFactory schedulerFactory;
        private readonly IJobFactory jobFactory;
        private readonly JobMetadata[] jobMetadatas;
        public CustomQuartzHostedService(ISchedulerFactory schedulerFactory, JobMetadata[] jobMetadata, IJobFactory jobFactory)
        {
            this.schedulerFactory = schedulerFactory;
            this.jobMetadatas = jobMetadata;
            this.jobFactory = jobFactory;
        }
        public IScheduler Scheduler { get; set; }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Scheduler = await schedulerFactory.GetScheduler();
            Scheduler.JobFactory = jobFactory;
            foreach (var jobMetadata in jobMetadatas)
            {
                var job = JobBuilder.Create(jobMetadata.JobType)
                    .WithIdentity(jobMetadata.JobId)
                    .WithDescription(jobMetadata.JobName)
                    .DisallowConcurrentExecution()
                    .Build();
                var trigger = TriggerBuilder.Create()
                    .WithIdentity(jobMetadata.JobId)
                    .WithCronSchedule(jobMetadata.CronExpression)
                    .WithDescription(jobMetadata.JobName)
                    .Build();
                await Scheduler.ScheduleJob(job, trigger, cancellationToken);
            }
            await Scheduler.Start(cancellationToken);

            //var job = CreateJob(jobMetadata);
            //var trigger = CreateTrigger(jobMetadata);
            //await Scheduler.ScheduleJob(job, trigger, cancellationToken);
            //await Scheduler.Start(cancellationToken);
        }
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Scheduler?.Shutdown(cancellationToken);
        }
        private ITrigger CreateTrigger(JobMetadata jobMetadata)
        {
            return TriggerBuilder.Create()
                                 .WithIdentity(jobMetadata.JobId.ToString())
                                 .WithCronSchedule(jobMetadata.CronExpression)
                                 .WithDescription($"{jobMetadata.JobName}")
                                 .Build();
        }
        private IJobDetail CreateJob(JobMetadata jobMetadata)
        {
            return JobBuilder
            .Create(jobMetadata.JobType)
            .WithIdentity(jobMetadata.JobId.ToString())
            .WithDescription($"{jobMetadata.JobName}")
            .Build();
        }
    }
}

三:修改启动配置:

var scheduler = StdSchedulerFactory.GetDefaultScheduler().GetAwaiter().GetResult();
            services.AddSingleton(scheduler);
            services.AddHostedService<CustomQuartzHostedService>();
            services.AddRazorPages();
            services.AddSingleton<IJobFactory, CustomQuartzJobFactory>();
            services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
            services.AddSingleton<NotificationJob>();
            //services.AddSingleton(new JobMetadata(Guid.NewGuid(), typeof(DataStatistics_MonthJob), "DataStatistics Job", "0 */1 * * * ?"));
            //多任务
            services.AddSingleton(new JobMetadata[]
            {
    new JobMetadata(Guid.NewGuid().ToString(), typeof(NotificationJob), "Notification Job", "0 */1 * * * ?"),
    new JobMetadata(Guid.NewGuid().ToString(), typeof(DataStatistics_MonthJob), "DataStatistics Job", "0 */1 * * * ?")
        });
            services.AddHostedService<CustomQuartzHostedService>();