.net core中Quartz的使用方法

网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要介绍了. core中Quartz的使用方法,长沙网络推广觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随长沙网络推广过来看看吧

原来工作中有用到定时任务Quartz,不过是在MVC项目中,现在 core项目中也要用到,就开始改版。中间发现在网上的教程只有执行定时计划的过程,却很少有人写注册的过程,觉得有点略坑。所以写此文章一是自己做个记录,二是希望能帮助到其他人。后面还把此功能做出了多任务定时执行,网上关于 core的教程更是少了,花费了不少时间实现了出来。

Quartz版本3.0.7

1.NuGet中下载安装Quartz

2.新建Quartz帮助类

(1)新建QuartzJob类,代码如下

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

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

ps 上面代码中的jobKey和triggerKey可获取到自己定义的job和trigger的信息,这样做多任务时可区分要执行的是哪个任务. 另LogHelper.Info是自己封装好的日子记录类,可替换为自己的日志类

(2)新建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)
    {
    }
  }

(3)新建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("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

3.在Startup.cs中注册代码

public void ConfigureServices(IServiceCollection services)
{
      services.AddQuartz(typeof(QuartzJob));

      //........
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  QuartzService.StartJobs<QuartzJob>();
  //........
}

 ps: 因AddQuartz方法定义的是Type[]类型,所以可传多个执行类,如services.AddQuartz(typeof(QuartzJob1), typeof(QuartzJob2)); 不过这样做StartJob()方法就得另处理下,这里就略过

OK,大功告成,这个东西折腾了两天终于尘埃落定了,执行结果如下

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by