Quartz.Net使用
标签:Quartz.Net
在最近工作中,需要在不同时间及不同条件下定时发送通知及消息,最初使用 System.Timers.Timer实现。虽然使用简单,随着需要定时处理的任务增多,考虑到 System.Timers.Timer如下缺点:
- Timer没有持久化机制;
- Timer的调度没有弹性,仅能定时触发,不可自由配置触发时间点;
- Timer不能利用线程池,每一个Timer需要开启一个线程;
- 每个Timer中的任务为串行执行,同一时间只能有一个任务在执行。前一个任务执行失败影响后面任务的执行;
而Quartz.Net的以下优点可解决以上问题
- 使用灵活,有多种使用方式(
egXML配置任务,及代码实现),且可以混合使用;- 支持集群,作业分组,及作业远程管理;
- 可自定义精细的时间管理;
- 支持数据库,可持久化。
安装
- 通过
NuGet安装Quartz.Net
说明
- 每一个任务需要继承接口
IJob,并实现Execute(IJobExecutionContext context),该方法为每个Job需要做的具体处理;
代码示例
- 代码创建job示例
1 private static void Main(string[] args) 2 { 3 try 4 { 5 WatchFile(); 6 var fileName = Path.Combine(Environment.CurrentDirectory, "log4config.config"); 7 XmlConfigurator.ConfigureAndWatch(new FileInfo(fileName)); 8 StdSchedulerFactory factory = new StdSchedulerFactory(); 9 IScheduler scheduler = factory.GetScheduler(); 10 // 启动任务 11 scheduler.Start(); 12 // 创建Job,可通过JobDataMap传递数据 13 IJobDetail job = JobBuilder.Create<HelloJob>() 14 .WithIdentity("job1", "group1") 15 .UsingJobData("jobSays", "Hello World!") 16 .UsingJobData("myFloatValue", 3.141f) 17 .Build(); 18 //创建trigger 19 ITrigger trigger = TriggerBuilder.Create() 20 .WithIdentity("trigger1", "group1") 21 .StartNow() 22 .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever()) 23 .Build(); 24 //把job,trigger加入调度器 25 scheduler.ScheduleJob(job, trigger); 26 //关闭调度器 27 scheduler.Shutdown(); 28 } 29 catch (Exception ex) 30 { 31 LogHelper.Error("Main" + ex); 32 } 33 Console.WriteLine("Press any key to close the application"); 34 Console.ReadKey(); 35 } 36 public class HelloJob : IJob 37 { 38 public void Execute(IJobExecutionContext context) 39 { 40 JobKey key = context.JobDetail.Key; 41 //获取执行的数据 42 JobDataMap dataMap = context.JobDetail.JobDataMap; 43 string jobSays = dataMap.GetString("jobSays"); 44 float myFloatValue = dataMap.GetFloat("myFloatValue"); 45 Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue); 46 47 } 48 } 49 pub
XML方式配置Job、Trigger代码示例 1) 在quartz_jobs.xml为配置Job及Trigger的文件 配置文件示例:
1<?xml version="1.0" encoding="utf-8" ?> 2<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> 3 <processing-directives> 4 <overwrite-existing-data>true</overwrite-existing-data> 5 </processing-directives> 6 <schedule> 7 <job> 8 <name>CommonIMRemindJob</name> 9 <group>IMRemindJob</group> 10 <description>IMRemindJob</description> 11 <job-type>NXIN.Qlw.JobServices.CommonIMRemindJobService,NXIN.Qlw.JobServices</job-type> 12 <durable>true</durable> 13 <recover>true</recover> 14 </job> 15 <trigger> 16 <simple> 17 <name>CommonIMRemindTrigger</name> 18 <group>IMRemindJob</group> 19 <description>CommonIMRemindTrigger</description> 20 <job-name>CommonIMRemindJob</job-name> 21 <job-group>IMRemindJob</job-group> 22 <misfire-instruction>SmartPolicy</misfire-instruction> 23 <repeat-count>-1</repeat-count> 24 <repeat-interval>300000</repeat-interval> 25 </simple> 26 </trigger> 27 </schedule> 28</job-scheduling-data> 29 30 312)实现示例 32 33 34 private static void InitScheduler() 35 { 36 try 37 { 38 NameValueCollection props = new NameValueCollection 39 { 40 { "quartz.serializer", "binary" } 41 }; 42 43 XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); 44 45 StdSchedulerFactory factory = new StdSchedulerFactory(props); 46 IScheduler scheduler = factory.GetScheduler(); 47 processor.ProcessFileAndScheduleJobs("~/quartz_jobs.xml", scheduler); 48 scheduler.Start(); 49 } 50 catch (SchedulerException se) 51 { 52 LogHelper.Error("/Main/RunProgramRunExample" + se); 53 } 54 }
参考博客:[蘑菇先生Net作业调度系列][1] [1]: http://www.cnblogs.com/mushroom/p/4850115.html