.NET core Quartz 定時任務框架 demo

開始先建個空的web項目。web

建立一個新類 QuartzFactory 狠狠的複製就完事了。mvc

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

QuartzJobapp

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;
        }
    }

QuartzServiceasync

  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

上面代碼中的一段代碼解讀ide

  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())ui

這裏面的  TimeSpan.FromSeconds(11)  是你定時的時間。this

也能夠定時天天的幾點。CronScheduleBuilder.DailyAtHourAndMinute(16, 10)  spa

這就是定時天天的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能夠用來區分任務的。

相關文章
相關標籤/搜索