1、需求場景:天天固定時間執行某個行爲/動做。app
一開始想用定時器,後來無心間發現了這個插件,感受功能太強大了,完美解決了個人問題。async
2、下載地址:https://www.quartz-scheduler.net/ui
3、使用方法spa
1.將剛纔下載的熱乎乎的dll引入到你的項目中.net
2.先寫你想定時執行的任務插件
1 public class ModifiyStateJob : IJob 2 { 3 Task IJob.Execute(IJobExecutionContext context) 4 { 5 Console.WriteLine("如今的時間是--{1}", DateTime.Now.ToString()); 6 return null; 7 } 8 }
3.用Quartz設置在天天的19:53執行該任務3d
1 public static async Task ListenTime() 2 { 3 try 4 { 5 // Grab the Scheduler instance from the Factory 6 NameValueCollection props = new NameValueCollection 7 { 8 { "quartz.serializer.type", "binary" } 9 }; 10 StdSchedulerFactory factory = new StdSchedulerFactory(props); 11 IScheduler scheduler = await factory.GetScheduler(); 12 13 // and start it off 14 await scheduler.Start(); 15 16 // define the job and tie it to our HelloJob class 17 // 18 IJobDetail job1 = JobBuilder.Create<TimeJob>() 19 .WithIdentity("job1", "group1") 20 .Build(); 21 22 24 //天天的19點53分執行 時間的順序是秒 分 小時 不要寫錯哦 25 ITrigger trigger1 = TriggerBuilder.Create() 26 .WithIdentity("trigger1", "group1") 27 .StartNow().WithCronSchedule("0 53 19 * * ?") 28 .Build(); 29 30 // Tell quartz to schedule the job using our trigger 31 await scheduler.ScheduleJob(job1, trigger1); 32 33 // some sleep to show what's happening 34 // await Task.Delay(TimeSpan.FromSeconds(60)); 35 36 // and last shut down the scheduler when you are ready to close your program 37 // await scheduler.Shutdown(); 38 } 39 catch (SchedulerException se) 40 { 41 Console.WriteLine(se); 42 } 43 44 45 }
4.在入口處進行調用code
1 static void Main(string[] args) 2 { 3 ListenTime().GetAwaiter().GetResult(); 4 Console.Read(); 5 }
5.效果(若是程序不關,則天天的19:53分都會運行該程序,在控制檯進行打印)blog
寫在後面的話:我只是用了Quartz的一個小功能,不管你是想固定時間執行任務,仍是間隔多長時間執行任務等等,Quartz.net都能知足你的需求,只要按照指定的規則編寫就能夠啦。string