在Quartz.Net中可能我们需要在某一时刻执行多个任务操作,而又不想创建多个任务。Quartz.Net为我们提供了多个ScheduleJob的重载来实现多个一次执行多个任务。
1 // 创建一个组任务的触发器,如果某个给定的任务或触发器已经存在(Job.Key不唯一)和replace为false时,就会抛出异常2 void ScheduleJob(IJobDetail jobDetail, ISettriggersForJob, bool replace);
利用这个方法可以创建一组任务来同时执行。
首先创建一个任务调度类:SystemScheduler。将创建好的每个任务设置好key之后加入到触发器组中
1 public class SystemScheduler 2 { 3 public static SystemScheduler CreateInstance() 4 { 5 return new SystemScheduler(); 6 } 7 8 private IScheduler _scheduler; 9 10 public void StartScheduler()11 {12 ISchedulerFactory schedulerFactory = new StdSchedulerFactory();13 _scheduler = schedulerFactory.GetScheduler();14 15 // 读取所有任务16 var jobs = Job.ReadJobs();17 if (jobs != null && jobs.Any())18 {19 // 创建一个触发器组对象20 Quartz.Collection.ISettriggers = new Quartz.Collection.HashSet ();21 22 //创建一个Job来执行特定的任务23 IJobDetail jobDetail = new JobDetailImpl("SettingHandler", typeof(SettingHandler));24 25 foreach (var job in jobs)26 {27 // 设置触发器key28 TriggerKey key = new TriggerKey(job.Key);29 30 //创建并定义触发器的规则(每天执行一次时间为:时,分)31 ITrigger trigger =32 TriggerBuilder.Create().WithIdentity(key)33 .WithDailyTimeIntervalSchedule(34 a => a.WithIntervalInHours(24).OnEveryDay().StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(job.Hour, job.Minute))).Build();35 triggers.Add(trigger);36 }37 _scheduler.ScheduleJob(jobDetail, triggers, true);38 39 //开始40 _scheduler.Start();41 }42 }43 44 /// 45 /// 停止任务46 /// 47 public void StopScheduler()48 {49 _scheduler.Shutdown();50 }51 }
创建任务处理类SettingHandler来执行任务:
public class SettingHandler : IJob { public void Execute(IJobExecutionContext context) { LogWriter.ToInfo(string.Format("{0} 开始执行设置CU任务", DateTime.Now.ToString())); try { UpdateTs.UpdateDt = DateTime.Now; Listjobs = Job.ReadJobs(); string jobKey = context.Trigger.Key.Name; // 获取任务 var job = jobs.FirstOrDefault(a => a.Key.Equals(jobKey)); if (job != null) { LogWriter.ToInfo("执行了一次任务:key=" + jobKey); // 任务处理逻辑 } } catch (Exception ex) { LogWriter.ToError("执行更新CU错误", ex); } } }
最后启动任务调度程序
private void Form1_Load(object sender, EventArgs e) { SystemScheduler systemScheduler = SystemScheduler.CreateInstance(); systemScheduler.StartScheduler(); }