在實際項目的開發過程中,會有這樣的功能需求:要求創建一些Job定時觸發運行,比如進行一些數據的同步。
那么在 .Net Framework 中如何實現這個Timer Job的功能呢?
這里所講的是借助第三方的組件 Quartz.Net 來實現(源碼位置:https://github.com/quartznet/quartznet)
詳細內容請看如下步驟:
1):首先在VS中創建一個Console Application,然后通過NuGet下載Quartz.Net組件並且引用到當前工程中。我們下載的是3.0版本,注:此版本與之前的2.0版本一定的區別。
2):繼承 IJob 接口,實現 Excute 方法
public class EricSimpleJob : IJob { public Task Execute(IJobExecutionContext context) { Console.WriteLine("Hello Eric, Job executed."); return Task.CompletedTask; } } public class EricAnotherSimpleJob : IJob { public Task Execute(IJobExecutionContext context) { string filepath = @"C:\timertest.txt"; if (!File.Exists(filepath)) { using (FileStream fs = File.Create(filepath)) { } } using (StreamWriter sw = new StreamWriter(filepath, true)) { sw.WriteLine(DateTime.Now.ToLongTimeString()); } return Task.CompletedTask; } }
3):完成 IScheduler, IJobDetails 與 ITrigger之間的配置
static async Task TestAsyncJob() { var props = new NameValueCollection { { "quartz.serializer.type", "binary" } }; StdSchedulerFactory schedFact = new StdSchedulerFactory(props); IScheduler sched = await schedFact.GetScheduler(); await sched.Start(); IJobDetail job = JobBuilder.Create<EricSimpleJob>() .WithIdentity("EricJob", "EricGroup") .Build(); IJobDetail anotherjob = JobBuilder.Create<EricAnotherSimpleJob>() .WithIdentity("EricAnotherJob", "EricGroup") .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("EricTrigger", "EricGroup") .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build(); ITrigger anothertrigger = TriggerBuilder.Create() .WithIdentity("EricAnotherTrigger", "EricGroup") .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build(); await sched.ScheduleJob(job, trigger); await sched.ScheduleJob(anotherjob, anothertrigger); }
4):在 Main 方法中完成調用, 由於是異步處理,因此這里用 Console.ReadKey() 完成對主線程的阻塞
static void Main(string[] args) { TestAsyncJob(); Console.ReadKey(); }
5):最終的運行結果為,兩個Job使屏幕和文件不斷輸出字符串
更多信息請參考如下鏈接:
https://www.cnblogs.com/MingQiu/p/8568143.html
6):如果我們想將此注冊為Windows Service,在對應Service啟動之后自動處理對應Job,請參考如下鏈接:
http://www.cnblogs.com/mingmingruyuedlut/p/9033159.html
如果是2.0版本的Quartz.Net請參考如下鏈接:
https://www.quartz-scheduler.net/download.html
https://www.codeproject.com/Articles/860893/Scheduling-With-Quartz-Net
https://stackoverflow.com/questions/8821535/simple-working-example-of-quartz-net