我们在日常开发中,总会遇到这样的需求:每隔一段时间,执行一次某个任务。固定某个时间执行任务,例如凌晨12点对当天的数据进行统计。每个月的第几天,执行某个任务。
Quartz.Net是根据Java的Quartz用C#改写而来,Quartz.NET是一个开源的作业调度框架,非常适合在平时的工作中,定时轮询数据库同步,定时邮件通知,定时处理数据等。Quartz.NET允许开发人员根据时间间隔来调度作业。
Quartz版本:3.3.2
1.NuGet中下载安装Quartz
2.新建Quartz帮助类
(1)新建JobSchedule类
public class JobSchedule{public JobSchedule(Type jobType, string cronExpression){JobType = jobType;CronExpression = cronExpression;}public Type JobType { get; }public string CronExpression { get; }
新建QuartzFactory类
public class QuartzFactory : IJobFactory{private readonly IServiceProvider _serviceProvider;public QuartzFactory(IServiceProvider serviceProvider){_serviceProvider = serviceProvider;}public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler){return _serviceProvider.GetRequiredService(bundle.JobDetail.JobType) as IJob;}public void ReturnJob(IJob job){ }
新建QuartzService类
public class QuartzHostedService : IHostedService{private readonly ISchedulerFactory _schedulerFactory;private readonly IJobFactory _jobFactory;private readonly IEnumerable<JobSchedule> _jobSchedules;public QuartzHostedService(ISchedulerFactory schedulerFactory,IJobFactory jobFactory,IEnumerable<JobSchedule> jobSchedules){_schedulerFactory = schedulerFactory;_jobSchedules = jobSchedules;_jobFactory = jobFactory;}public IScheduler Scheduler { get; set; }public async Task StartAsync(CancellationToken cancellationToken){Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);Scheduler.JobFactory = _jobFactory;foreach (var jobSchedule in _jobSchedules){var job = CreateJob(jobSchedule);var trigger = CreateTrigger(jobSchedule);await Scheduler.ScheduleJob(job, trigger, cancellationToken);}await Scheduler.Start(cancellationToken);}public async Task StopAsync(CancellationToken cancellationToken){await Scheduler?.Shutdown(cancellationToken);}private static IJobDetail CreateJob(JobSchedule schedule){var jobType = schedule.JobType;return JobBuilder.Create(jobType).WithIdentity(jobType.FullName).WithDescription(jobType.Name).Build();}private static ITrigger CreateTrigger(JobSchedule schedule){return TriggerBuilder.Create().WithIdentity($"{schedule.JobType.FullName}.trigger").WithCronSchedule(schedule.CronExpression).WithDescription(schedule.CronExpression).Build();}}
在Startup.cs中注册代码
services.AddControllers();#region Quartz Service// Add Quartz servicesservices.AddSingleton<IJobFactory, QuartzFactory>();services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();// Add our jobservices.AddTransient<DeleteFileJob>();services.AddJob();services.AddHostedService<QuartzHostedService>();
Quartz.Net源码:
https://github.com/quartznet/quartznet
官方学习文档:
http://www.quartz-scheduler.net/documentation/index.html