前一篇隨筆講了Quartz單任務的簡單實現,這一篇咱們來說講多任務的實現html
主要看下面這段代碼,這是Quartz多任務調度的方法,主要就是圍繞這個方法去擴展:app
// // 摘要: // Schedule all of the given jobs with the related set of triggers. // // 言論: // If any of the given jobs or triggers already exist (or more specifically, if // the keys are not unique) and the replace parameter is not set to true then an // exception will be thrown. Task ScheduleJobs(IReadOnlyDictionary<IJobDetail, IReadOnlyCollection<ITrigger>> triggersAndJobs, bool replace, CancellationToken cancellationToken = default);
一、首先咱們建兩個任務類:async
using System; using System.Threading.Tasks; using Quartz; namespace HHF.Quartz { public class Task_1 : IJob { public Task Execute(IJobExecutionContext context) { return Console.Out.WriteLineAsync($"這是任務一,執行時間:{DateTime.Now}"); } } }
二、改造一下以前的QuartzScheduler類,添加一個GetJobs方法,生成任務集合post
1 /// <summary> 2 /// 很Low的一段代碼 3 /// </summary> 4 /// <returns></returns> 5 public List<IJobDetail> GetJobs() 6 { 7 IJobDetail job1 = JobBuilder.Create<Task_1>() 8 .WithIdentity("job1") 9 .Build(); 10 IJobDetail job2 = JobBuilder.Create<Task_2>() 11 .WithIdentity("job3") 12 .Build(); 13 return new List<IJobDetail>() { job1, job2 }; 14 }
三、改造一下Run方法ui
1 /// <summary> 2 /// 任務調度的使用過程 3 /// </summary> 4 /// <returns></returns> 5 public async static Task Run() 6 { 7 // 建立scheduler的引用 8 ISchedulerFactory schedFact = new StdSchedulerFactory(); 9 IScheduler sched = await schedFact.GetScheduler(); 10 11 // 獲取job集合 12 var jobs = GetJobs(); 13 // 申明一個任務與觸發器映射的字典集合 14 var jobAndTriggerMapping = new Dictionary<IJobDetail, IReadOnlyCollection<ITrigger>>(); 15 // 遍歷任務列表 16 for (int i = 0; i < jobs.Count; i++) 17 { 18 var job = jobs[i]; 19 // 只讀的觸發器集合 20 var triggers = new ReadOnlyCollection<ITrigger>( 21 new List<ITrigger>() 22 { 23 TriggerBuilder.Create() 24 .WithIdentity("trigger_"+i) 25 .WithSimpleSchedule(x => x.WithIntervalInSeconds(i+5).RepeatForever()) 26 .Build() 27 }); 28 // 創建映射關係 29 jobAndTriggerMapping[job] = triggers; 30 } 31 // 將映射關係包裝成制度字典集合 32 var readOnlyjobAndTriggerMapping = new ReadOnlyDictionary<IJobDetail, IReadOnlyCollection<ITrigger>>(jobAndTriggerMapping); 33 34 /* 35 * 使用trigger規劃執行任務job 36 *第二個參數replace:若是爲true,則指定的觸發器或者任務名稱已經存在將會替換,不然將拋出異常 37 */ 38 await sched.ScheduleJobs(readOnlyjobAndTriggerMapping, true); 39 40 // 啓動 scheduler 41 await sched.Start(); 42 }
四、查看執行結果,咱們能夠看到,任務一的執行間隔時間爲5秒,任務二的執行間隔時間爲6秒,能夠正常執行。url