在實際項目的開發過程當中,會有這樣的功能需求:要求建立一些Job定時觸發運行,好比進行一些數據的同步。html
那麼在 .Net Framework 中如何實現這個Timer Job的功能呢?git
這裏所講的是藉助第三方的組件 Quartz.Net 來實現(源碼位置:https://github.com/quartznet/quartznet)github
詳細內容請看以下步驟:異步
1):首先在VS中建立一個Console Application,而後經過NuGet下載Quartz.Net組件而且引用到當前工程中。咱們下載的是3.0版本,注:此版本與以前的2.0版本必定的區別。async
2):繼承 IJob 接口,實現 Excute 方法ui
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之間的配置spa
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() 完成對主線程的阻塞.net
static void Main(string[] args) { TestAsyncJob(); Console.ReadKey(); }
5):最終的運行結果爲,兩個Job使屏幕和文件不斷輸出字符串線程
更多信息請參考以下連接:code
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