/// <summary> /// Push一个作业 /// </summary> /// <param name="model"></param> public static void PushJobDetail(int taskId) { #region Job var job = dal.GetModel(taskId); var jobNum = string.Format("job_{0}", taskId); if (scheduler.CheckExists(new JobKey(jobNum))) { scheduler.DeleteJob(new JobKey(jobNum)); } var dic3 = new Dictionary <string, ModelTask>(); dic3.Add(jobNum, job); //把运行任务添加到任务队列中 IJobDetail job3 = JobBuilder.Create <JobDetailHelper>() .WithIdentity(jobNum) .SetJobData(new JobDataMap(dic3)) .Build(); #endregion #region 调度器 Quartz.Collection.ISet <ITrigger> ll = new Quartz.Collection.HashSet <ITrigger>(); //添加到调度器中 var triggerNum = string.Format("trigger_{0}", taskId); var t3 = TriggerBuilder.Create(); t3.WithIdentity(triggerNum); t3.WithCronSchedule(job.PlanFormat);//"0/5 * * * * ?" var trigger3 = t3.Build(); //scheduler.ScheduleJob(job3, trigger3); ll.Add(trigger3); #endregion scheduler.ScheduleJob(job3, ll, true); }
private void QuartzScheduleJob(Job job) { IDictionary jobDataDictionary = new Dictionary <string, object> { { "jobId", job.Id.ToString() } }; var jobDetail = JobBuilder.Create <JobsDistributor>() .WithIdentity(job.Id.ToString()) .SetJobData(new JobDataMap(jobDataDictionary)) .Build(); var triggers = new Quartz.Collection.HashSet <ITrigger>(); foreach (var jobTrigger in job.Triggers) { var trigger = TriggerBuilder.Create() .WithIdentity(Guid.NewGuid().ToString()) .WithCronSchedule(jobTrigger.Cron) .Build(); triggers.Add(trigger); } _scheduler.ScheduleJob(jobDetail, triggers, true); }
/// <summary> /// 优先级调用(数字越大优先级越高) /// </summary> public static void Fun7() { var sche = StdSchedulerFactory.GetDefaultScheduler(); sche.Start(); var job = JobBuilder.Create <MyJob>() .Build(); //trigger var trigger = TriggerBuilder.Create().StartNow() .WithPriority(1) .UsingJobData("Name", "Trigger1") .EndAt(DateTimeOffset.Now.AddMinutes(1)) //在一分钟后关闭触发器 .WithSimpleSchedule(m => m.WithIntervalInSeconds(1).RepeatForever()) .Build(); //trigger2 var trigger2 = TriggerBuilder.Create().StartNow() .WithPriority(999999) .UsingJobData("Name", "Trigger2") .EndAt(DateTimeOffset.Now.AddMinutes(1)) //在一分钟后关闭触发器 .WithSimpleSchedule(m => m.WithIntervalInSeconds(1).RepeatForever()) .Build(); //Quartz.Collection.HashSet<ITrigger> list = new HashSet<ITrigger>(); Quartz.Collection.HashSet <ITrigger> list = new Quartz.Collection.HashSet <ITrigger>(); list.Add(trigger); list.Add(trigger2); sche.ScheduleJob(job, list, true); }
public static Quartz.Collection.ISet <ITrigger> BuildTriggers(IJobSchedule schedule) { if (schedule == null || schedule.Triggers == null) { return(null); } var errors = new List <string>(); var set = new Quartz.Collection.HashSet <ITrigger>(schedule.Triggers.Select(t => { try { return(ParseTrigger(t)); } catch (Exception ex) { errors.Add(ex.Message); return(null); } }).Where(t => t != null)); if (errors.Count > 0) { Log.Error("Trigger Creation Errors: \n" + string.Join("\n", errors)); } return(set); }
/// <summary> /// Reminder for crossroads /// </summary> private void Crossroads() { IJobDetail job = JobBuilder.Create<MycroftJob>() .WithIdentity("crossroadsJob") .UsingJobData("phrase", "Crossroads is closing in 20 minutes") .Build(); job.JobDataMap.Add("client", this); Quartz.Collection.HashSet<ITrigger> set = new Quartz.Collection.HashSet<ITrigger>(); set.Add(TriggerBuilder.Create() .WithIdentity("crossroadsWeekday") .WithCronSchedule("0 40 21 ? * MON-THU") .Build()); set.Add(TriggerBuilder.Create() .WithIdentity("crossroadsFriday") .WithCronSchedule("0 40 17 ? * FRI") .Build()); set.Add(TriggerBuilder.Create() .WithIdentity("crossroadsSunday") .WithCronSchedule("0 40 19 ? * SUN") .Build()); scheduler.ScheduleJob(job, set, true); }
public override TriggerPropertyBundle CreatePropertyBundle() { DailyTimeIntervalScheduleBuilder scheduleBuilder = DailyTimeIntervalScheduleBuilder.Create() .WithInterval(RepeatInterval, RepeatIntervalUnit) .WithRepeatCount(RepeatCount); if (DaysOfWeek.Any()) { Quartz.Collection.ISet<DayOfWeek> daysOfWeek = new Quartz.Collection.HashSet<DayOfWeek>(); foreach (var dayOfWeek in DaysOfWeek) { daysOfWeek.Add(dayOfWeek); } scheduleBuilder.OnDaysOfTheWeek(daysOfWeek); } else { scheduleBuilder.OnDaysOfTheWeek(DailyTimeIntervalScheduleBuilder.AllDaysOfTheWeek); } scheduleBuilder.StartingDailyAt(StartTimeOfDay ?? TimeOfDay.HourMinuteAndSecondOfDay(0, 0, 0)); scheduleBuilder.EndingDailyAt(EndTimeOfDay ?? TimeOfDay.HourMinuteAndSecondOfDay(23, 59, 59)); string[] statePropertyNames = { "timesTriggered" }; object[] statePropertyValues = { TimesTriggered }; return new TriggerPropertyBundle(scheduleBuilder, statePropertyNames, statePropertyValues); }
public static string GetNextRunAtMessages(this IJobDetail job, Quartz.Collection.HashSet <ITrigger> triggers) { string targetTimeZone = (string)job.JobDataMap[Constants.FieldNames.Timezone]; TimeZoneInfo timezone = TimeZoneInfo.Local; if (!string.IsNullOrEmpty(targetTimeZone)) { timezone = TimeZoneInfo.FindSystemTimeZoneById(targetTimeZone); } string runPlan = string.Empty; foreach (ITrigger t in triggers) { if (t.GetNextFireTimeUtc().HasValue) { var nextFireTimeUtc = t.GetNextFireTimeUtc().Value; var nextFireTimeInTargetTimeZone = TimeZoneInfo.ConvertTimeFromUtc(nextFireTimeUtc.DateTime, timezone); var nextFireTimeInLocalTimeZone = TimeZoneInfo.ConvertTimeFromUtc(nextFireTimeUtc.DateTime, TimeZoneInfo.Local); string timeZoneName = timezone.IsDaylightSavingTime(nextFireTimeUtc) ? timezone.DaylightName : timezone.StandardName; string localTimeZoneName = TimeZone.CurrentTimeZone.IsDaylightSavingTime(nextFireTimeInTargetTimeZone) ? TimeZone.CurrentTimeZone.DaylightName : TimeZone.CurrentTimeZone.StandardName; if (timeZoneName != localTimeZoneName) { runPlan += $"{nextFireTimeInTargetTimeZone:F} {timeZoneName} ({nextFireTimeInLocalTimeZone:F} {localTimeZoneName}){Environment.NewLine}"; } else { runPlan += $"{nextFireTimeInTargetTimeZone:F} {timeZoneName}{Environment.NewLine}"; } } else { runPlan = $"Job does not have a next run time set"; } } if (string.IsNullOrEmpty(runPlan)) { runPlan = $"Job does not have a specific trigger"; } return(runPlan); }
public static void CreateJob(string tenant, Event @event) { var alarmStop = @event.Until ?? @event.EndsOn; if (@event.Alarm == null || @event.Alarm.Value == 0 || @event.StartsAt >= alarmStop) { return; } int reminderBeforeMinutes = @event.Alarm.Value; var factory = new StdSchedulerFactory(); var scheduler = factory.GetScheduler(); scheduler.Start(); var map = new JobDataMap { new KeyValuePair <string, object>("Event", @event), new KeyValuePair <string, object>("Tenant", tenant) }; var job = JobBuilder.Create <ReminderJob>() .WithIdentity(@event.EventId.ToString(), tenant) .SetJobData(map) .Build(); var icalEvent = @event.ToIcalEvent(); var occurences = icalEvent.GetOccurrences(@event.StartsAt.DateTime, alarmStop.DateTime).ToList(); var recurringDates = occurences.Select(x => x.Period.StartTime.Value); var startTime = @event.StartsAt.TimeOfDay; var triggers = new Quartz.Collection.HashSet <ITrigger>(); foreach (var eventDate in recurringDates) { var triggerTime = eventDate.Date.Add(startTime).AddMinutes(reminderBeforeMinutes * -1); var trigger = TriggerBuilder.Create() .StartAt(triggerTime) .Build(); triggers.Add(trigger); } scheduler.ScheduleJob(job, triggers, true); }
//public void AddRelation(TriggerRelation poTriggerRelation) //{ // if (this.moScheduler != null) // { // var loList = TriggerRepository.Instance.Read(); // loList.Remove(poTriggerRelation); // loList.Add(poTriggerRelation); // TriggerRepository.Instance.Write(loList); // var loJobKey = this.moScheduler.GetJobKeys(GroupMatcher<JobKey>.GroupContains(poTriggerRelation.Group)).FirstOrDefault(item => item.Name == poTriggerRelation.JobName); // if (loJobKey != null) // { // CronTriggerImpl loTrigger = new CronTriggerImpl(poTriggerRelation.TriggerName, poTriggerRelation.Group, poTriggerRelation.CronExpression); // loTrigger.JobKey = loJobKey; // if (this.moScheduler.GetTriggersOfJob(loJobKey).Any(item => item.Key.Name == loTrigger.Key.Name && item.Key.Group == loTrigger.Key.Group)) // this.moScheduler.RescheduleJob(loTrigger.Key, loTrigger); // else // this.moScheduler.ScheduleJob(loTrigger); // } // } //} public void AddRelation(JobRelation poJobRelation) { if (this.moScheduler != null) { var loSchedulerJob = MefExporter.Instance.GetSchedulerJob(poJobRelation.Type); if (loSchedulerJob != null) { Quartz.Collection.HashSet <ITrigger> loTriggerSet = new Quartz.Collection.HashSet <ITrigger>(); loTriggerSet.Add(new CronTriggerImpl("Trg. for {0}".FormatWith(poJobRelation.JobName), poJobRelation.Group, poJobRelation.CronExpression)); var loJobDetail = new JobDetailImpl(poJobRelation.JobName, poJobRelation.Group, loSchedulerJob.GetType()); loJobDetail.Description = loSchedulerJob.Description; loJobDetail.JobDataMap.Add(Constants.JobConfigEntry, poJobRelation.JsonConfig); this.moScheduler.ScheduleJob(loJobDetail, loTriggerSet, true); } } }
public void ScheduleJobsWithTriggers(IEnumerable <IIntegrationJobTrigger> triggerDefs, Type jobType, IJobDetail jobDetail) { if (!triggerDefs.Any()) { return; } var triggersForJobs = new Quartz.Collection.HashSet <ITrigger>(); foreach (var triggerDef in triggerDefs) { triggersForJobs.Add(TriggerFactory(triggerDef as CronTrigger, jobType, jobDetail)); } Scheduler.ScheduleJob(jobDetail, triggersForJobs, true); foreach (var triggerDef in triggerDefs) { SetTriggerState(TriggerKeyFactory(triggerDef.Id, jobType), triggerDef.StateId); } }
/// <summary> /// 载入所有作业 /// </summary> public static void LoadAllJobs() { DataTable dt = dal.GetList(" And IsPlan=1 ").Tables[0]; //DataTable dt = dal.GetList("Order By Id Asc").Tables[0]; if (dt != null && dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { #region Job var job = dal.GetModel(int.Parse(dr["Id"].ToString())); if (string.IsNullOrEmpty(job.PlanFormat)) { continue; } var jobNum = string.Format("job_{0}", dr["Id"].ToString()); if (scheduler.CheckExists(new JobKey(jobNum))) { continue; } var dic3 = new Dictionary <string, ModelTask>(); dic3.Add(jobNum, job); IJobDetail job3 = JobBuilder.Create <JobDetailHelper>() .WithIdentity(jobNum) .SetJobData(new JobDataMap(dic3)) .Build(); #endregion #region 调度器 Quartz.Collection.ISet <ITrigger> ll = new Quartz.Collection.HashSet <ITrigger>(); var triggerNum = string.Format("trigger_{0}", dr["Id"].ToString()); var t3 = TriggerBuilder.Create(); t3.WithIdentity(triggerNum); t3.WithCronSchedule(job.PlanFormat);//"0/5 * * * * ?" var trigger3 = t3.Build(); //scheduler.ScheduleJob(job3, trigger3); ll.Add(trigger3); #endregion scheduler.ScheduleJob(job3, ll, true); } } }
/// <summary> /// Update the corresponding scheduling job for a a trigger on schedule, recreating the triggers. /// </summary> /// <param name="scheduledItem"></param> public static void UpdateScheduledJob(ScheduledItem scheduledItem, IScheduler scheduler) { var deleteJob = false; if (scheduledItem.TriggerEnabled ?? true) { var action = scheduledItem.IsOfType.First(t => t.Is <ScheduleAction>()); var jobClass = action.As <ScheduleAction>().OnScheduleFire.GetClass(); var job = JobBuilder.Create(jobClass) .WithIdentity(GetJobId(scheduledItem)) .WithDescription(scheduledItem.Name) .RequestRecovery(true) .UsingCurrentTenant() .UsingScheduledItemJobData(scheduledItem) .Build(); var oneOffJobs = CreateOneOffJobs(scheduledItem); var dailyRepeats = CreateDailyRepeats(scheduledItem); var cronJobs = CreateCron(scheduledItem); var allTriggers = new Quartz.Collection.HashSet <ITrigger>(oneOffJobs.Union(dailyRepeats).Union(cronJobs)); if (allTriggers.Count > 0) { scheduler.ScheduleJob(job, allTriggers, true); // replace any existing jobs. } else { deleteJob = true; } } else { deleteJob = true; } if (deleteJob) { DeleteScheduledJob(scheduledItem.Id, SchedulingHelper.Instance); } }
static void Main(string[] args) { logger.InfoFormat("{0:D3}.{1}", ++numberIndex, MethodBase.GetCurrentMethod().Name); var scheduler = StdSchedulerFactory.GetDefaultScheduler(); var jobDetail = JobBuilder.Create <TestJob1>() .WithIdentity("statistic1", "statistic") .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("statistic1", "statistic") .WithSimpleSchedule(ssb => ssb.WithIntervalInSeconds(3).RepeatForever()) .Build(); var triggers = new Quartz.Collection.HashSet <ITrigger>(); triggers.Add(trigger); scheduler.ScheduleJob(jobDetail, triggers, true); scheduler.Start(); Console.ReadKey(); }
private static Quartz.Collection.ISet <ITrigger> BuildTriggers(SchJob job) { var utcDate = DateTime.UtcNow; var res = new Quartz.Collection.HashSet <ITrigger>(); foreach (var trigger in job.Job_SchTrigger_List) { if (trigger.Disabled == true) { continue; } if (utcDate < trigger.StartTimeUtc || trigger.EndTimeUtc <= utcDate) { continue; } res.Add(BuildTrigger(trigger)); } return(res); }
private static Quartz.Collection.ISet <ITrigger> GetTriggers(ISchJob job, Func <ISchTrigger, bool> validateHandler = null) { var res = new Quartz.Collection.HashSet <ITrigger>(); foreach (var trigger in job.Job_Trigger_List) { if (validateHandler != null && !validateHandler(trigger)) { continue; } var qtrigger = GetTrigger(trigger); if (qtrigger == null) { continue; } res.Add(qtrigger); } return(res); }
private static IEnumerable <ITrigger> CreateDailyRepeats(ScheduledItem scheduledItem) { var dailyRepeats = scheduledItem.ScheduleForTrigger.Select(sch => sch.As <ScheduleDailyRepeat>()) .Where(sch => sch != null); var result = new Quartz.Collection.HashSet <ITrigger>(); foreach (var dailyRepeat in dailyRepeats) { if (dailyRepeat.SdrTimeOfDay != null) { // TODO: This should not be converted to local time but to the TZ of the original creator. We currently do not store that infomation. var sdrTimeOfDay = ((DateTime)dailyRepeat.SdrTimeOfDay); var timeOfDay = new TimeOfDay(sdrTimeOfDay.Hour, sdrTimeOfDay.Minute, sdrTimeOfDay.Second); var timeZone = TimeZoneHelper.GetTimeZoneInfo(dailyRepeat.SdrTimeZone); var daysOfWeek = dailyRepeat.GetRelationships("core:sdrDayOfWeek").Entities.Select(dayEnumVal => (int)dayEnumVal.GetField("core:enumOrder")); if (!daysOfWeek.Any()) { daysOfWeek = Enumerable.Range(0, 7); } var dow = daysOfWeek.Select(i => (DayOfWeek)i).ToArray(); var qtrigger = TriggerBuilder.Create() .WithIdentity(GetTriggerKey(scheduledItem, dailyRepeat)) .WithDailyTimeIntervalSchedule( x => x .OnDaysOfTheWeek(dow) .StartingDailyAt(timeOfDay) .WithInterval(24, IntervalUnit.Hour).InTimeZone(timeZone)) .Build(); result.Add(qtrigger); } } return(result); }
public static Quartz.Collection.HashSet <ITrigger> CreateTriggers(this IJobDetail job) { string runAt = (string)job.JobDataMap[Constants.FieldNames.RunAt]; string runOnDays = (string)job.JobDataMap[Constants.FieldNames.RunDays]; string runCalendar = (string)job.JobDataMap[Constants.FieldNames.RunCalendar]; string excludeCalendar = (string)job.JobDataMap[Constants.FieldNames.ExclusionCalendar]; string targetTimeZone = (string)job.JobDataMap[Constants.FieldNames.Timezone]; var triggers = new Quartz.Collection.HashSet <ITrigger>(); string[] runAtTimes = runAt.Split(','); int runAtIndex = 0; foreach (var runAtTime in runAtTimes) { string triggerName = $"Trigger_{runAtIndex++}_for_{job.Key}"; var trigger = CreateTriggerForSpecificRunTime(triggerName, runAtTime, runOnDays, excludeCalendar, targetTimeZone); triggers.Add(trigger); } return(triggers); }
/// <summary> /// Updates job /// </summary> /// <param name="jobName"></param> /// <param name="message"></param> public static void UpdateJob(string jobName, string message, Enumerations.MaintenanceJobType jobType, string jobMailSubject = "", string jobMailBody = "") { log.Info("About to update local job"); log.Info("Getting related trigger"); ICronTrigger realtedTrigger = GetCronTriggerForJob(GetAllJobs().FirstOrDefault(jd => jd.Key.Name == jobName).Key); log.Info("Trigger retrived successfuly"); log.Info("Creating new job instance"); IJobDetail newJob = CreateJobBasedOnItsType(jobName, message, jobType, jobMailSubject, jobMailBody); log.Info("Job instance created"); Quartz.Collection.ISet <ITrigger> trigger = new Quartz.Collection.HashSet <ITrigger>(); try { log.Info("Creating trigger for a newJob"); trigger.Add(TriggerBuilder.Create() .ForJob(newJob) .WithIdentity(realtedTrigger.Key.Name) .WithCronSchedule(realtedTrigger.CronExpressionString) .StartAt(realtedTrigger.StartTimeUtc) .Build()); } catch (Exception ex) { log.Error(ex.Message, ex); } log.Info("Replacing job and trigger"); try { scheduler.ScheduleJob(newJob, trigger, true); } catch (SchedulerException SchEx) { log.Error(SchEx.Message, SchEx); } log.Info("Job and trigger successfuly replaced"); }
/// <summary> /// 添加 任务 直接使用 /// </summary> /// <param name="jobDetail">任务处理模块</param> /// <param name="triggerList">触发器集合</param> /// <param name="IsRun">是否直接开启</param> /// <param name="error">错误消息</param> /// <returns>返回结果</returns> public bool AddQuartzServer(IJobDetail jobDetail, Quartz.Collection.HashSet <ITrigger> triggerList, out string error, bool IsRun = true) { bool result = true; error = ""; try { scheduler.ScheduleJob(jobDetail, triggerList, false); if (IsRun) { scheduler.ResumeJob(jobDetail.Key); } } catch (Exception ex) { error += ex.Message; result = false; } UpdateJobsTriggerList(jobDetail.Key); return(result); }
public void Execute(IJobExecutionContext context) { Log.LogToConsole("Checking for updates"); if (CheckForUpdates()) { Log.LogToConsole("Update found"); context.Scheduler.PauseTrigger(context.Trigger.Key); ITrigger trigger; Quartz.Collection.ISet <ITrigger> triggers = new Quartz.Collection.HashSet <ITrigger>(); switch (Settings.Instance.UpdateType) { case 1: context.Scheduler.TriggerJob(new JobKey("Update")); break; case 2: context.Scheduler.TriggerJob(new JobKey("Broadcast"), new JobDataMap { { "Message", Settings.Instance.UpdateFoundMessage.Replace("%minutes%", Settings.Instance.WaitTime.ToString()) } }); if (Settings.Instance.WaitTime > 10) { trigger = TriggerBuilder.Create() .StartAt(DateBuilder.FutureDate(Settings.Instance.WaitTime - 10, IntervalUnit.Minute)) .ForJob(context.Scheduler.GetJobDetail(new JobKey("Broadcast"))) .UsingJobData("Message", Settings.Instance.TenMinutesMessage.Replace("%minutes%", "10")) .Build(); triggers.Add(trigger); } // Trigger for one Minute before trigger = TriggerBuilder.Create() .StartAt(DateBuilder.FutureDate(Settings.Instance.WaitTime - 1, IntervalUnit.Minute)) .ForJob(context.Scheduler.GetJobDetail(new JobKey("Broadcast"))) .UsingJobData("Message", Settings.Instance.OneMinuteMessage.Replace("%minutes%", "1")) .Build(); triggers.Add(trigger); context.Scheduler.ScheduleJob(context.Scheduler.GetJobDetail(new JobKey("Broadcast")), triggers, true); trigger = TriggerBuilder.Create() .StartAt(DateBuilder.FutureDate(Settings.Instance.WaitTime, IntervalUnit.Minute)) .ForJob(context.Scheduler.GetJobDetail(new JobKey("Update"))) .Build(); context.Scheduler.ScheduleJob(trigger); break; case 3: context.Scheduler.TriggerJob(new JobKey("Broadcast"), new JobDataMap { { "Message", Settings.Instance.UpdateFoundMessage.Replace("%minutes%", Settings.Instance.WaitTime.ToString()) } }); trigger = TriggerBuilder.Create() .WithSimpleSchedule(x => x .WithIntervalInMinutes(5) .RepeatForever()) .ForJob(context.Scheduler.GetJobDetail(new JobKey("CheckForPlayers"))) .StartNow() .Build(); context.Scheduler.ScheduleJob(trigger); break; } } else { Log.LogToConsole("No update available"); } }
public void ScheduleJobs() { try { //start a scheduler var schedulerMetaData = scheduler.GetMetaData(); Log.Info("Scheduler Metadata Summary =>", this); Log.Info(schedulerMetaData.GetSummary(), this); Log.Info("SchedulerInstanceId : " + schedulerMetaData.SchedulerInstanceId, this); Log.Info("SchedulerName : " + schedulerMetaData.SchedulerName, this); Log.Info("ThreadPoolSize : " + schedulerMetaData.ThreadPoolSize, this); Log.Info("ThreadPoolType: " + schedulerMetaData.ThreadPoolType.ToString(), this); Log.Info("JobStoreType: " + schedulerMetaData.JobStoreType.ToString(), this); scheduler.Start(); //Create Job Definitions and add it to the collection to simulate this is what we will get from Sitecore Log.Info("Getting Job Definitions", this); var jobDefinitions = GetConfiguredJobs(); //Cleanup any existing jobs scheduled already //to ensure that every time ScheduleJobs is called, //it schedules the whole list of jobs from fresh Log.Info("Clearing existing scheduled Jobs before we set it up agin !", this); scheduler.Clear(); if (jobDefinitions != null && jobDefinitions.Count > 0) { foreach (JobDetail jd in jobDefinitions) { //if (jd.JobKey.Equals("Cleanup Publish Queue")) //{ JobDataMap jobDataMap = new JobDataMap(); //Get Job Data Map NameValueCollection jobDataCollection = Sitecore.Web.WebUtil.ParseUrlParameters(jd.JobData); foreach (string key in jobDataCollection.Keys) { jobDataMap.Add(key, jobDataCollection[key]); } // define the job and tie it to our HelloJob class var job = JobBuilder.Create(Type.GetType(jd.Type, true, true)) .WithIdentity(jd.JobKey, jd.Group) .WithDescription(jd.Description) .UsingJobData(jobDataMap) .Build(); Log.Info(String.Format("Job {0} created", jd.JobKey), this); Log.Info(String.Format("Getting triggers for job {0}", jd.JobKey), this); var triggersForJob = GetTriggersForJob(jd); Quartz.Collection.HashSet<ITrigger> triggers = new Quartz.Collection.HashSet<ITrigger>(); ITriggerListener trigListener = new SchedulerTriggerListener(); #region "Looping through trigger Details" foreach (TriggerDetail td in triggersForJob) { TriggerBuilder trigger = GetTriggerBuilder(jd, td); //Add Job and Trigger listeners Log.Info("Registering Trigger Listener", this); scheduler.ListenerManager.AddTriggerListener(trigListener, EverythingMatcher<JobKey>.AllTriggers()); triggers.Add(trigger.Build()); Log.Info(String.Format("Job {0} is being scheduled with trigger {1}.", jd.JobKey, td.TriggerKey), this); } #endregion try { scheduler.ScheduleJob(job, triggers, true); } catch (JobExecutionException jobExeEX) { Log.Error(String.Format("Sitecore.QuartzScheuler: Error Occured in {0}", jobExeEX.Source) + jobExeEX.Message + Environment.NewLine + jobExeEX.StackTrace, this); } catch (SchedulerException schedulerEx) { Log.Error(String.Format("Sitecore.QuartzScheuler: Error Occured in {0}", schedulerEx.Source) + schedulerEx.Message + Environment.NewLine + schedulerEx.StackTrace, this); } catch (Exception ex) { Log.Error(String.Format("Sitecore.QuartzScheuler: Error occured while schedule job {0}", jd.JobKey), this); Log.Error("Sitecore.QuartzScheuler: " + ex.Message + Environment.NewLine + ex.StackTrace, this); } } } else { Log.Info("No Jobs found. No jobs will be scheduled.", this); } //} } catch (Exception ex) { Log.Error("Sitecore.QuartzScheuler: " + ex.Message + Environment.NewLine + ex.StackTrace, this); } }
public void ScheduleJobs() { try { //start a scheduler var schedulerMetaData = scheduler.GetMetaData(); Log.Info("Scheduler Metadata Summary =>", this); Log.Info(schedulerMetaData.GetSummary(), this); Log.Info("SchedulerInstanceId : " + schedulerMetaData.SchedulerInstanceId, this); Log.Info("SchedulerName : " + schedulerMetaData.SchedulerName, this); Log.Info("ThreadPoolSize : " + schedulerMetaData.ThreadPoolSize, this); Log.Info("ThreadPoolType: " + schedulerMetaData.ThreadPoolType.ToString(), this); Log.Info("JobStoreType: " + schedulerMetaData.JobStoreType.ToString(), this); scheduler.Start(); //Create Job Definitions and add it to the collection to simulate this is what we will get from Sitecore Log.Info("Getting Job Definitions", this); var jobDefinitions = GetConfiguredJobs(); //Cleanup any existing jobs scheduled already //to ensure that every time ScheduleJobs is called, //it schedules the whole list of jobs from fresh Log.Info("Clearing existing scheduled Jobs before we set it up agin !", this); scheduler.Clear(); if (jobDefinitions != null && jobDefinitions.Count > 0) { foreach (JobDetail jd in jobDefinitions) { //if (jd.JobKey.Equals("Cleanup Publish Queue")) //{ JobDataMap jobDataMap = new JobDataMap(); //Get Job Data Map NameValueCollection jobDataCollection = Sitecore.Web.WebUtil.ParseUrlParameters(jd.JobData); foreach (string key in jobDataCollection.Keys) { jobDataMap.Add(key, jobDataCollection[key]); } // define the job and tie it to our HelloJob class var job = JobBuilder.Create(Type.GetType(jd.Type, true, true)) .WithIdentity(jd.JobKey, jd.Group) .WithDescription(jd.Description) .UsingJobData(jobDataMap) .Build(); Log.Info(String.Format("Job {0} created", jd.JobKey), this); Log.Info(String.Format("Getting triggers for job {0}", jd.JobKey), this); var triggersForJob = GetTriggersForJob(jd); Quartz.Collection.HashSet <ITrigger> triggers = new Quartz.Collection.HashSet <ITrigger>(); ITriggerListener trigListener = new SchedulerTriggerListener(); #region "Looping through trigger Details" foreach (TriggerDetail td in triggersForJob) { TriggerBuilder trigger = GetTriggerBuilder(jd, td); //Add Job and Trigger listeners Log.Info("Registering Trigger Listener", this); scheduler.ListenerManager.AddTriggerListener(trigListener, EverythingMatcher <JobKey> .AllTriggers()); triggers.Add(trigger.Build()); Log.Info(String.Format("Job {0} is being scheduled with trigger {1}.", jd.JobKey, td.TriggerKey), this); } #endregion try { scheduler.ScheduleJob(job, triggers, true); } catch (JobExecutionException jobExeEX) { Log.Error(String.Format("Sitecore.QuartzScheuler: Error Occured in {0}", jobExeEX.Source) + jobExeEX.Message + Environment.NewLine + jobExeEX.StackTrace, this); } catch (SchedulerException schedulerEx) { Log.Error(String.Format("Sitecore.QuartzScheuler: Error Occured in {0}", schedulerEx.Source) + schedulerEx.Message + Environment.NewLine + schedulerEx.StackTrace, this); } catch (Exception ex) { Log.Error(String.Format("Sitecore.QuartzScheuler: Error occured while schedule job {0}", jd.JobKey), this); Log.Error("Sitecore.QuartzScheuler: " + ex.Message + Environment.NewLine + ex.StackTrace, this); } } } else { Log.Info("No Jobs found. No jobs will be scheduled.", this); } //} } catch (Exception ex) { Log.Error("Sitecore.QuartzScheuler: " + ex.Message + Environment.NewLine + ex.StackTrace, this); } }
private static void Main(string[] args) { ConfigureIoc(); var schedFact = new StdSchedulerFactory(); var scheduler = schedFact.GetScheduler(); //BootStrapTwitterHistoryFromFile(TinyIoCContainer.Current.Resolve<ITwitterHistoryRepository>()); scheduler.JobFactory = new InjectingJobFactory(); scheduler.Start(); var rssScraperJob = JobBuilder.Create<RssScraper>().Build(); var rssScraperTrigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithIntervalInSeconds(120).RepeatForever()).Build(); var twitterScraperJob = JobBuilder.Create<TwitterScraper>().Build(); var twitterScraperTrigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithIntervalInMinutes(5).RepeatForever()).Build(); var rateLimitLoggerJob = JobBuilder.Create<TwitterRateLimitLogger>().Build(); var twitterRateLimitTrigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithIntervalInMinutes(1).RepeatForever()).Build(); var twitterActionJob = JobBuilder.Create<TwitterActionHandler>().Build(); var twitterActionTriggers = new Quartz.Collection.HashSet<ITrigger>() { BuildSpecificTimeTrigger(08,30), BuildSpecificTimeTrigger(11,00), BuildSpecificTimeTrigger(12,30), BuildSpecificTimeTrigger(14,00), BuildSpecificTimeTrigger(16,30), BuildSpecificTimeTrigger(18,00), BuildSpecificTimeTrigger(20,00) }; scheduler.ScheduleJob(rssScraperJob, rssScraperTrigger); scheduler.ScheduleJob(twitterActionJob, twitterActionTriggers, true); scheduler.ScheduleJob(twitterScraperJob, twitterScraperTrigger); //scheduler.ScheduleJob(rateLimitLoggerJob, twitterRateLimitTrigger); new ManualResetEvent(false).WaitOne(); }
public void Add() { if (this.JobType == null) { MessageBox.Show("请选择任务类型"); return; } if (!this.ReplaceExists) { if (this.Scheduler.CheckExists(new TriggerKey(this.TriggerName, this.TriggerGroup))) { MessageBox.Show("指定的触发器已经存在,请重新指定名称"); return; } if (this.Scheduler.CheckExists(new JobKey(this.JobName, this.JobGroup))) { MessageBox.Show("指定的任务已经存在,请重新指定名称"); return; } } try { var jobBuilder = JobBuilder.Create(this.JobType) .WithIdentity(this.JobName, this.JobGroup) .WithDescription(this.JobDesc); var scheduleBuilder = this.ScheduleBuildByVM.GetScheduleBuilder(); var triggerBuilder = TriggerBuilder.Create() .WithSchedule(scheduleBuilder) .WithIdentity(this.TriggerName, this.TriggerGroup) .WithPriority(this.TriggerPriority) .WithDescription(this.TriggerDesc); var datamap = new JobDataMap(); foreach (var p in this.Parameters) { datamap.Put(p.Key, p.Value); } if (datamap.Count > 0) { jobBuilder.UsingJobData(datamap); } if (!string.IsNullOrWhiteSpace(this.ChoicedCalendar)) { triggerBuilder.ModifiedByCalendar(this.ChoicedCalendar); } // 如果是用 AdoStore , 修改一个已经存在的 Trigger 的 ScheduleBuilder 到不同的类型,任务会报错, // 这里如果是不同的类型,先删除 var storType = this.Scheduler.GetMetaData().JobStoreType; if (storType.Equals(typeof(JobStoreTX)) && this.OrgScheduleBuilderType != null && !this.OrgScheduleBuilderType.Equals(scheduleBuilder.GetType()) ) { var key = new JobKey(this.JobName, this.JobGroup); this.Scheduler.DeleteJob(key); } if (this.ReplaceExists) { var triggers = new Quartz.Collection.HashSet <ITrigger>(); triggers.Add(triggerBuilder.Build()); this.Scheduler.ScheduleJob(jobBuilder.Build(), triggers, true); } else { var jd = jobBuilder.Build(); var t = triggerBuilder.Build(); this.Scheduler.ScheduleJob(jd, t); //this.Scheduler.ScheduleJob(jobBuilder.Build(), triggerBuilder.Build()); } MessageBox.Show("保存成功"); } catch (Exception ex) { MessageBox.Show(ex.GetBaseException().Message); } }
/// <summary> /// Reminder for Ctrl Alt Deli /// </summary> private void CtrlAltDeli() { IJobDetail job = JobBuilder.Create<MycroftJob>() .WithIdentity("ctrlAltDeliJob") .UsingJobData("phrase", "Control Alt Deli is closing in 20 minutes") .Build(); job.JobDataMap.Add("client", this); Quartz.Collection.HashSet<ITrigger> set = new Quartz.Collection.HashSet<ITrigger>(); set.Add(TriggerBuilder.Create() .WithIdentity("ctrlAltDeliWeekday") .WithCronSchedule("0 10 18 ? * MON-THU") .Build()); set.Add(TriggerBuilder.Create() .WithIdentity("ctrlAltDeliFriday") .WithCronSchedule("0 40 14 ? * FRI") .Build()); scheduler.ScheduleJob(job, set, true); }
public void Add() { if (this.JobType == null) { MessageBox.Show("请选择任务类型"); return; } if (!this.ReplaceExists) { if (this.Scheduler.CheckExists(new TriggerKey(this.TriggerName, this.TriggerGroup))) { MessageBox.Show("指定的触发器已经存在,请重新指定名称"); return; } if (this.Scheduler.CheckExists(new JobKey(this.JobName, this.JobGroup))) { MessageBox.Show("指定的任务已经存在,请重新指定名称"); return; } } try { var jobBuilder = JobBuilder.Create(this.JobType) .WithIdentity(this.JobName, this.JobGroup) .WithDescription(this.JobDesc); var scheduleBuilder = this.ScheduleBuildByVM.GetScheduleBuilder(); var triggerBuilder = TriggerBuilder.Create() .WithSchedule(scheduleBuilder) .WithIdentity(this.TriggerName, this.TriggerGroup) .WithPriority(this.TriggerPriority) .WithDescription(this.TriggerDesc); var datamap = new JobDataMap(); foreach (var p in this.Parameters) { datamap.Put(p.Key, p.Value); } if (datamap.Count > 0) jobBuilder.UsingJobData(datamap); if (!string.IsNullOrWhiteSpace(this.ChoicedCalendar)) triggerBuilder.ModifiedByCalendar(this.ChoicedCalendar); // 如果是用 AdoStore , 修改一个已经存在的 Trigger 的 ScheduleBuilder 到不同的类型,任务会报错, // 这里如果是不同的类型,先删除 var storType = this.Scheduler.GetMetaData().JobStoreType; if (storType.Equals(typeof(JobStoreTX)) && this.OrgScheduleBuilderType != null && !this.OrgScheduleBuilderType.Equals(scheduleBuilder.GetType()) ) { var key = new JobKey(this.JobName, this.JobGroup); this.Scheduler.DeleteJob(key); } if (this.ReplaceExists) { var triggers = new Quartz.Collection.HashSet<ITrigger>(); triggers.Add(triggerBuilder.Build()); this.Scheduler.ScheduleJob(jobBuilder.Build(), triggers, true); } else { var jd = jobBuilder.Build(); var t = triggerBuilder.Build(); this.Scheduler.ScheduleJob(jd, t); //this.Scheduler.ScheduleJob(jobBuilder.Build(), triggerBuilder.Build()); } MessageBox.Show("保存成功"); } catch (Exception ex) { MessageBox.Show(ex.GetBaseException().Message); } }
private static Quartz.Collection.ISet<ITrigger> GetTriggers(ISchJob job, Func<ISchTrigger, bool> validateHandler = null) { var res = new Quartz.Collection.HashSet<ITrigger>(); foreach (var trigger in job.Job_Trigger_List) { if (validateHandler != null && !validateHandler(trigger)) continue; var qtrigger = GetTrigger(trigger); if (qtrigger == null) continue; res.Add(qtrigger); } return res; }