本文由[【小居工作室】原创,转载请说明源地址:http://www.cnblogs.com/wjs5943283/p/7076178.html,感谢如鹏网老杨的技术教学和细心指导。特此说明!
Quartz.net(2.5.0)用起来感觉很麻烦,就写个辅助类,先写两个方法,别的用到可再扩展,写的不到之处,再请指出:
/// <summary> /// 定时器辅助类 /// </summary> public static class QuartzHelper { private static readonly IScheduler Sched = new StdSchedulerFactory().GetScheduler(); /// <summary> /// 基于CronScheduleBuilder,在某一时刻执行job /// </summary> /// <param name="jobType">Ijob实现类</param> /// <param name="builder">CronScheduleBuilder对象</param> /// <param name="jobName">job名称,不能重复</param> /// <param name="triggerKeyName">trigger名称,不能重复</param> public static void CronScheduleQuartz(Type jobType, CronScheduleBuilder builder, string jobName=null, string triggerKeyName=null) { if (string.IsNullOrWhiteSpace(jobName)) { jobName = Guid.NewGuid().ToString(); } if (string.IsNullOrWhiteSpace(triggerKeyName)) { triggerKeyName = Guid.NewGuid().ToString(); } JobDetailImpl jdBossReport = new JobDetailImpl(jobName, jobType); IMutableTrigger triggerBossReport = builder.Build(); triggerBossReport.Key = new TriggerKey(triggerKeyName); Sched.ScheduleJob(jdBossReport, triggerBossReport); } /// <summary> /// 基于CalendarIntervalScheduleBuilder,每隔多久执行一次job /// </summary> /// <param name="jobType">Ijob实现类</param> /// <param name="builder">CalendarIntervalScheduleBuilder对象</param> /// <param name="jobName">job名称,不能重复</param> /// <param name="triggerKeyName">trigger名称,不能重复</param> public static void CalendarIntervalQuartz(Type jobType, CalendarIntervalScheduleBuilder builder, string jobName = null, string triggerKeyName = null) { if (string.IsNullOrWhiteSpace(jobName)) { jobName = Guid.NewGuid().ToString(); } if (string.IsNullOrWhiteSpace(triggerKeyName)) { triggerKeyName = Guid.NewGuid().ToString(); } JobDetailImpl jdBossReport = new JobDetailImpl(jobName, jobType); IMutableTrigger triggerBossReport = builder.Build(); triggerBossReport.Key = new TriggerKey(triggerKeyName); Sched.ScheduleJob(jdBossReport, triggerBossReport); } /// <summary> /// 执行定时任务 /// </summary> public static void Start() { Sched.Start(); } }
调用方法:
QuartzHelper.CalendarIntervalQuartz(typeof(MyJob1), CalendarIntervalScheduleBuilder.Create().WithInterval(3,IntervalUnit.Second), "myjob1", "t1"); QuartzHelper.CronScheduleQuartz(typeof(MyJob2),CronScheduleBuilder.DailyAtHourAndMinute(9,41),"myjob2","t2" ); QuartzHelper.CalendarIntervalQuartz(typeof(MyJob), CalendarIntervalScheduleBuilder.Create().WithInterval(2, IntervalUnit.Second)); QuartzHelper.CronScheduleQuartz(typeof(MyJob1), CronScheduleBuilder.DailyAtHourAndMinute(9, 41)); QuartzHelper.Start();