.net 6 配置QuartZ定时任务的过程

  ///

  /// 添加任务和触发器

  ///

  ///

  ///

  ///

  ///

  public static void AddJobAndTrigger(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config) where T : IJob

  {

  // Use the name of the IJob as the appsettings.json key

  string jobName = typeof(T).Name;

  // Try and load the schedule from configuration

  var configKey = $"Quartz:{jobName}";

  var cronSchedule = config[configKey];

  // Some minor validation

  if (string.IsNullOrEmpty(cronSchedule))

  {

  throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");

  }

  // register the job as before

  var jobKey = new JobKey(jobName);

  quartz.AddJob(opts => opts.WithIdentity(jobKey));

  quartz.AddTrigger(opts => opts

  .ForJob(jobKey)

  .WithIdentity(jobName + "-trigger")

  .WithCronSchedule(cronSchedule)); // use the schedule from configuration

  }

  ///

  /// 添加任务和触发器(带参数传递)

  ///

  ///

  ///

  ///

  /// 需要传递的参数

  /// 默认通过 工作描述时传递参数

  ///

  public static void AddJobAndTriggerWithParameter(this IServiceCollectionQuartzConfigurator quartz, IConfiguration config,

  IDictionary? keyValuePairs = null, bool isJobDetailJobDataMap = true) where T : IJob

  {

  // Use the name of the IJob as the appsettings.json key

  string jobName = typeof(T).Name;

  // Try and load the schedule from configuration

  var configKey = $"Quartz:{jobName}";

  var cronSchedule = config[configKey];

  // Some minor validation

  if (string.IsNullOrEmpty(cronSchedule))

  {

  throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");

  }

  // register the job as before

  var jobKey = new JobKey(jobName);

  if (keyValuePairs != null && isJobDetailJobDataMap)

  {

  switch (isJobDetailJobDataMap)

  {

  case true:

  quartz.AddJob(opts => opts

  .WithIdentity(jobKey)

  .UsingJobData(new JobDataMap(keyValuePairs)));

  quartz.AddTrigger(opts => opts

  .ForJob(jobKey)

  .WithIdentity(jobName + "-trigger")

  .WithCronSchedule(cronSchedule)); // use the schedule from configuration

  break;

  case false:

  quartz.AddJob(opts => opts

  .WithIdentity(jobKey));

  quartz.AddTrigger(opts => opts

  .ForJob(jobKey)

  .WithIdentity(jobName + "-trigger")

  .WithCronSchedule(cronSchedule)

  .UsingJobData(new JobDataMap(keyValuePairs))); // use the schedule from configuration

  break;

  }

  }

  else

  {

  quartz.AddJob(opts => opts

  .WithIdentity(jobKey));

  quartz.AddTrigger(opts => opts

  .ForJob(jobKey)

  .WithIdentity(jobName + "-trigger")

  .WithCronSchedule(cronSchedule)); // use the schedule from configuration

  }

  }