引入 Quartz NuGet 包
新建 IJobFactory 继承类 控制Job
public class DefaultScheduleServiceFactory : IJobFactory { /// <summary> /// 容器提供器, /// </summary> protected IServiceProvider _serviceProvider; /// <summary> /// 构造函数 /// </summary> /// <param name="serviceProvider"></param> public DefaultScheduleServiceFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <summary> /// 返回IJob /// </summary> /// <param name="bundle"></param> /// <param name="scheduler"></param> /// <returns></returns> public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { //Job类型 Type jobType = bundle.JobDetail.JobType; //返回jobType对应类型的实例 return _serviceProvider.GetService(jobType) as IJob; } /// <summary> /// 清理销毁IJob /// </summary> /// <param name="job"></param> public void ReturnJob(IJob job) { var disposable = job as IDisposable; disposable?.Dispose(); } }
新建 Job 工厂类 QuartzHostedService
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(); } }
创建 Job 参数类
public class JobSchedule { public JobSchedule(Type jobType, string cronExpression) { JobType = jobType; CronExpression = cronExpression; } public Type JobType { get; } public string CronExpression { get; } }
创建 任务配置类 QuartzService
public static class QuartzService { #region 单任务 public static void StartJob<TJob>(string jobName,int time) where TJob : IJob { var scheduler = new StdSchedulerFactory().GetScheduler().Result; var job = JobBuilder.Create<TJob>() .WithIdentity(jobName) .Build(); var trigger1 = TriggerBuilder.Create() .WithIdentity("job."+ jobName) .StartNow() .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMinutes(time)).RepeatForever()) .ForJob(job) .Build(); scheduler.AddJob(job, true); scheduler.ScheduleJob(job, trigger1); scheduler.Start(); } #endregion #region 多任务 public static void StartJobs<TJob>() where TJob : IJob { var scheduler = new StdSchedulerFactory().GetScheduler().Result; var job = JobBuilder.Create<TJob>() .WithIdentity("jobs") .Build(); var trigger1 = TriggerBuilder.Create() .WithIdentity("job.trigger1") .StartNow() .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMinutes(5)).RepeatForever()) .ForJob(job) .Build(); var trigger2 = TriggerBuilder.Create() .WithIdentity("job.trigger2") .StartNow() .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMinutes(11)).RepeatForever()) .ForJob(job) .Build(); var dictionary = new Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>> { {job, new HashSet<ITrigger> {trigger1, trigger2}} }; scheduler.ScheduleJobs(dictionary, true); scheduler.Start(); } #endregion #region 配置 public static void AddQuartz(this IServiceCollection services, params Type[] jobs) { services.AddSingleton<IJobFactory, DefaultScheduleServiceFactory>(); services.Add(jobs.Select(jobType => new ServiceDescriptor(jobType, jobType, ServiceLifetime.Singleton))); services.AddSingleton(provider => { var schedulerFactory = new StdSchedulerFactory(); var scheduler = schedulerFactory.GetScheduler().Result; scheduler.JobFactory = provider.GetService<IJobFactory>(); scheduler.Start(); return scheduler; }); } #endregion }
新建 Job 实现类
/// <summary> /// 创建IJob的实现类,并实现Excute方法。 /// </summary> public class MyJob : IJob { private readonly IConfiguration _configuration; public MyJob(IConfiguration configuration) => this._configuration = configuration; public async Task Execute(IJobExecutionContext context) { await Task.CompletedTask; } }
Startup 注入
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); #region 定时任务 注入 services.AddSingleton(typeof(MyJob)); services.AddSingleton<MyJob>(); services.AddHostedService<QuartzHostedService>(); services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>(); services.AddSingleton<IJobFactory, DefaultScheduleServiceFactory>(); #endregion services.Configure<AppSettings>(Configuration); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { #region 定时任务 执行 QuartzService.StartJob<MyJob>("MyJob", 1); #endregion if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }