参照了:https://www.cnblogs.com/dangzhensheng/p/10496278.html
1.新建任务类ReportJob.cs,这个类里就是具体任务了。
using Quartz; using System; using System.IO; using System.Threading.Tasks; namespace WebApplication1.MyQuartzJob { /// <summary> /// 具体任务类 /// </summary> [DisallowConcurrentExecution] public class ReportJob : IJob { public Task Execute(IJobExecutionContext context) { return Task.Run(() => { foo(); }); } public void foo() { try { string root = Directory.GetCurrentDirectory(); string logDir = Path.Combine(root, "Logs"); logDir = Path.Combine(logDir, DateTime.Now.ToString("yyyy-MM")); var reportDirectory = logDir; if (!Directory.Exists(reportDirectory)) { Directory.CreateDirectory(reportDirectory); } var dailyReportFullPath = Path.Combine(reportDirectory, DateTime.Now.ToString("yyyy-MM-dd")+".txt"); var logContent = string.Format("{0}==>>{1}{2}", DateTime.Now, "create new log.", Environment.NewLine); File.AppendAllText(dailyReportFullPath, logContent); } catch (Exception ex) { //日志 } } } }
foo() 方法就是想要做的任务。
2.新建QuartzFactory类,这个类复制粘贴就行。
using Quartz; using Quartz.Spi; using System; namespace WebApplication1.MyQuartzJob { /// <summary> /// 工厂,复制就行 /// </summary> public class QuartzFactory : IJobFactory { private readonly IServiceProvider _serviceProvider; public QuartzFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { var jobDetail = bundle.JobDetail; var job = (IJob)_serviceProvider.GetService(jobDetail.JobType); return job; } public void ReturnJob(IJob job) { } } }
3.新建QuartzService类,本类用来定时,和对IServiceCollection进行配置。
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Quartz; using Quartz.Impl; using Quartz.Spi; using System; using System.Collections.Generic; using System.Linq; namespace WebApplication1.MyQuartzJob { /// <summary> /// 制定任务,配置IServiceCollection /// </summary> public static class QuartzService { #region 单任务 public static void StartJob<TJob>() where TJob : IJob { string thisJob = "ReportJob"; string groupName = "gp" + thisJob; string jobName = "job" + thisJob; string triggerName = "trigger" + thisJob; var scheduler = new StdSchedulerFactory().GetScheduler().Result; var job = JobBuilder.Create<TJob>() .WithIdentity(jobName, groupName) .Build(); var trigger1 = TriggerBuilder.Create() .WithIdentity(triggerName, groupName) .StartNow() .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).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.FromSeconds(5)).RepeatForever()) .ForJob(job) .Build(); var trigger2 = TriggerBuilder.Create() .WithIdentity("job.trigger2") .StartNow() .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(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, QuartzFactory>(); 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 } }
StartJob 是制定任务,AddQuartz 配置IServiceCollection。
4.在Startup.cs中注册代码
(a) 在public void ConfigureServices(IServiceCollection services) 方法尾部添加一行:services.AddQuartz(typeof(ReportJob));
public void ConfigureServices(IServiceCollection services) { // 。。。。 services.AddQuartz(typeof(ReportJob)); }
注意要引用QuartzService类的命名空间。
(b)在 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 方法尾部添加一行:QuartzService.StartJob<ReportJob>();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //.... QuartzService.StartJob<ReportJob>(); }
5. F5 运行。