C# Quartz 调度任务辅助类
1 public class QuartzHelper 2 { 3 /// <summary> 4 /// 时间间隔执行任务 5 /// </summary> 6 /// <typeparam name="T">任务类,必须实现IJob接口</typeparam> 7 /// <param name="seconds">时间间隔(单位:毫秒)</param> 8 public static void ExecuteInterval<T>(int seconds) where T : IJob 9 { 10 ISchedulerFactory factory = new StdSchedulerFactory(); 11 IScheduler scheduler = factory.GetScheduler(); 12 13 //IJobDetail job = JobBuilder.Create<T>().WithIdentity("job1", "group1").Build(); 14 IJobDetail job = JobBuilder.Create<T>().Build(); 15 16 ITrigger trigger = TriggerBuilder.Create() 17 .StartNow() 18 .WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).RepeatForever()) 19 .Build(); 20 21 scheduler.ScheduleJob(job, trigger); 22 23 scheduler.Start(); 24 } 25 26 /// <summary> 27 /// 指定时间执行任务 28 /// </summary> 29 /// <typeparam name="T">任务类,必须实现IJob接口</typeparam> 30 /// <param name="cronExpression">cron表达式,即指定时间点的表达式</param> 31 public static void ExecuteByCron<T>(string cronExpression) where T : IJob 32 { 33 ISchedulerFactory factory = new StdSchedulerFactory(); 34 IScheduler scheduler = factory.GetScheduler(); 35 36 IJobDetail job = JobBuilder.Create<T>().Build(); 37 38 //DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(DateTime.Now.AddSeconds(1), 2); 39 //DateTimeOffset endTime = DateBuilder.NextGivenSecondDate(DateTime.Now.AddYears(2), 3); 40 41 ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create() 42 //.StartAt(startTime).EndAt(endTime) 43 .WithCronSchedule(cronExpression) 44 .Build(); 45 46 scheduler.ScheduleJob(job, trigger); 47 48 scheduler.Start(); 49 50 //Thread.Sleep(TimeSpan.FromDays(2)); 51 //scheduler.Shutdown(); 52 } 53 } 54 55 public class TimeJob1 : IJob 56 { 57 public void Execute(IJobExecutionContext context) 58 { 59 Log.Info("", "调度任务TimeJob1开始工作"); 60 } 61 }