.NET core Quartz 定时任务框架 demo

开始先建个空的web项目。

创建一个新类 QuartzFactory 狠狠的复制就完事了。

  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)
        {
        }
    }

QuartzJob

public class QuartzJob : IJob
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        public async Task Execute(IJobExecutionContext context)
        {
            var jobKey = context.JobDetail.Key;//获取job信息
            var triggerKey = context.Trigger.Key;//获取trigger信息   --jobWork1  --jobWork2

            logger.Info($"{DateTime.Now} QuartzJob:==>>自动执行\r\n.{jobKey.Name}|{triggerKey.Name}\r\n");
            await Task.CompletedTask;
        }
    }

QuartzService

  public static class QuartzService
    {
        #region 单任务
        public static void StartJob<TJob>() where TJob : IJob
        {
          var scheduler = new StdSchedulerFactory().GetScheduler().Result;
 
          var job = JobBuilder.Create<TJob>()
            .WithIdentity("job")
            .Build();
 
          var trigger1 = TriggerBuilder.Create()
            .WithIdentity("job.trigger")
            .StartNow()
            .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(5)).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("jobWork1")
            .StartNow()
            .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(5)).RepeatForever())
            .ForJob(job)
            .Build();
 
          var trigger2 = TriggerBuilder.Create()
            .WithIdentity("jobWork2")
            .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
    }
View Code

上面代码中的一段代码解读

  var trigger2 = TriggerBuilder.Create()
      .WithIdentity("jobWork2")
      .StartNow()
      .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(11)).RepeatForever())
      .ForJob(job)
      .Build();


WithIdentity()
括号里面的字符串到时候会传到QuartzJob类,
我是主要是用这个字符串来判断你所定时执行的某个作业某个任务。

 

WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(11)).RepeatForever())

这里面的  TimeSpan.FromSeconds(11)  是你定时的时间。

也可以定时每天的几点。.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(16, 10))

这就是定时每天的16点10分执行当然你复制完这些类没用的。因为是core项目 还是要注册任务的。

 


Startup类
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();   //注册mvc服务  
            services.AddQuartz(typeof(QuartzJob));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //使用NLog作为日志记录工具
            loggerFactory.AddNLog();
            //引入Nlog配置文件
            env.ConfigureNLog("Nlog.config");

            QuartzService.StartJobs<QuartzJob>();  //多任务

            //QuartzService.StartJob<QuartzJob>();  //单任务

            app.UseMvc(routes => {     //开启mvc
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}"
                    );
            });
        }

这样就可以运行了。

 

因为我写的是demo  用的是日志Nlog。

 

 可以看到是jobWork1和2可以用来区分任务的。

 

posted @ 2019-10-30 17:06  亚俊  阅读(1578)  评论(0编辑  收藏  举报