Quartz.NET除了支持前面几篇讲的持续时间式的任务外,还支持日历式的任务,日历式的任务主要应用场景比如一些节假日或者特定纪念日的任务执行或排除。主要通过
AnnualCalendar 类来控制。
代码如下:
public class SimpleJob : IJob
{
private static readonly ILog log = LogManager.GetLogger(typeof(SimpleJob));
public virtual void Execute(IJobExecutionContext context)
{
JobKey jobKey = context.JobDetail.Key;
log.InfoFormat(" {0} 执行时间 {1}", jobKey, System.DateTime.Now.ToString());
}
}
public class CalendarExample
{
public static void Run()
{
ILog log = LogManager.GetLogger(typeof (CalendarExample));
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler sched = sf.GetScheduler();
AnnualCalendar holidays = new AnnualCalendar();
DateTime fourthOfJuly = new DateTime(DateTime.UtcNow.Year, 3, 15);
holidays.SetDayExcluded(fourthOfJuly, true);
DateTime halloween = new DateTime(DateTime.UtcNow.Year, 10, 31);
holidays.SetDayExcluded(halloween, true);
DateTime christmas = new DateTime(DateTime.UtcNow.Year, 12, 25);
holidays.SetDayExcluded(christmas, true);
sched.AddCalendar("holidays", holidays, false, false);
IJobDetail job = JobBuilder.Create<SimpleJob>()
.WithIdentity("job1", "group1")
.Build();
ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever())
.ModifiedByCalendar("holidays")
.Build();
DateTimeOffset ft = sched.ScheduleJob(job, trigger);
log.Info(string.Format("{0} 开始时间 {1} 重复次数 {2}, 间隔时间 {3}", job.Key, ft.ToString(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));
sched.Start();
log.Info("------- 开始计划 ----------------");
Thread.Sleep(30*1000);
sched.Shutdown(true);
log.Info("------- 关闭计划 -----------------");
SchedulerMetaData metaData = sched.GetMetaData();
log.Info(string.Format("执行次数{0}", metaData.NumberOfJobsExecuted));
}
}
其中
holidays.SetDayExcluded(fourthOfJuly, true);
表示排除该日期,如果第二个参数传false表示包括该日期。ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever())
.ModifiedByCalendar("holidays")
.Build();
ModifiedByCalendar("holidays")表示应用这个日历的一些设置。