任务并发属性
[DisallowConcurrentExecution] 添加属性后,任务不支持并发,只有上个任务执行完毕,下个任务才开始执行(如果定时10s,10s执行完毕,下个任务在10s后执行,如果执行时间超过10s,任务执行完毕后才开始下个任务)
using Quartz; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace WeiBatcher { [PersistJobDataAfterExecution] //使job有状态 public class ConcurrentJob : IJob { private readonly ExecuteService executeService; //继承自IJob,必须显性声明一个无参构造函数,否则Quartz 的job不能初始化,因此不能使用依赖注入 public ConcurrentJob() { executeService = new ExecuteService(); } /// <summary> /// 作业调度定时执行的方法 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Execute(IJobExecutionContext context) { await executeService.Execute(context); } } }
public async static Task<bool> GetSchedulers(SchedulerConfig config,bool resume=false) { //通过设置job的附加属性,标识job的业务函数 var jobDataMap = new JobDataMap(); //jobDataMap.Add(config.JobConfig.JobDataMapKey, config.JobConfig.JobName); jobDataMap.Add("ServiceName", config.JobConfig.ServiceName); JobBuilder jobBuilder; if (config.JobConfig.Concurrent) { jobBuilder = JobBuilder.Create<ConcurrentJob>(); } else { jobBuilder = JobBuilder.Create<WeiBatcherJob>(); } // 创建一个作业 IJobDetail job = jobBuilder .WithIdentity(config.JobConfig.JobName, config.JobConfig.JobGroup) .UsingJobData(jobDataMap) .StoreDurably() .Build(); var item = config.TriggerConfigs; //创建一个触发器 ITrigger trig = TriggerBuilder.Create() .WithIdentity(item.TriggerName, item.TriggerGroup) .WithCalendarIntervalSchedule(w => { if (item.WithIntervalInSeconds > 0) { w.WithIntervalInSeconds(item.WithIntervalInSeconds); } else if (item.WithIntervalInMinutes > 0) { w.WithIntervalInMinutes(item.WithIntervalInMinutes); } else if (item.WithIntervalInHours > 0) { w.WithIntervalInHours(item.WithIntervalInHours); } else if (item.WithIntervalInDays > 0) { w.WithIntervalInDays(item.WithIntervalInDays); } else if (item.WithIntervalInMonths > 0) { w.WithInterval(item.WithIntervalInMonths, IntervalUnit.Month); } //之前丢失的立即补执行一次,之后执行时间点和周期不会发生变化 w.WithMisfireHandlingInstructionFireAndProceed(); }) .WithPriority(item.Priority) .Build(); if (! await scheduler.CheckExists(job.Key)) await scheduler.ScheduleJob(job, trig); if (resume) { await scheduler.ResumeTrigger(trig.Key); } return true; }

浙公网安备 33010602011771号