private static triggerType GetTriggerType(ITrigger trigger, JobKey jobKey) { triggerType triggerType = new triggerType(); cronTriggerType cronTrigger = new cronTriggerType(); cronTrigger.priority = trigger.Priority.ToString(); cronTrigger.name = trigger.Key.Name; cronTrigger.calendarname = trigger.CalendarName.TrimEmptyToNull(); cronTrigger.description = trigger.Description; cronTrigger.misfireinstruction = GetCronMisfireInstruction(trigger.MisfireInstruction); if (trigger.EndTimeUtc != null) { cronTrigger.endtime = trigger.EndTimeUtc.Value.DateTime; cronTrigger.endtimeSpecified = true; } else { cronTrigger.endtimeSpecified = false; } cronTrigger.group = trigger.Key.Group; if (trigger.JobKey != null) { cronTrigger.jobname = trigger.JobKey.Name; cronTrigger.jobgroup = trigger.JobKey.Group; } else { cronTrigger.jobname = jobKey.Name; cronTrigger.jobgroup = jobKey.Group; } if (trigger is ICronTrigger cTrigger) { cronTrigger.cronexpression = cTrigger.CronExpressionString.TrimEmptyToNull(); cronTrigger.timezone = cTrigger.TimeZone.Id; } if (trigger.JobDataMap != null && trigger.JobDataMap.Count > 0) { cronTrigger.jobdatamap = new jobdatamapType(); cronTrigger.jobdatamap.entry = GetEntryTypes(trigger.JobDataMap); } triggerType.Item = cronTrigger; return(triggerType); }
protected virtual void ProcessInternal(string xml) { PrepForProcessing(); ValidateXml(xml); MaybeThrowValidationException(); // deserialize as object model XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); if (data == null) { throw new SchedulerConfigException("Job definition data from XML was null after deserialization"); } // // Extract pre-processing commands // if (data.preprocessingcommands != null) { foreach (preprocessingcommandsType command in data.preprocessingcommands) { if (command.deletejobsingroup != null) { foreach (string s in command.deletejobsingroup) { string deleteJobGroup = s.NullSafeTrim(); if (!String.IsNullOrEmpty(deleteJobGroup)) { jobGroupsToDelete.Add(deleteJobGroup); } } } if (command.deletetriggersingroup != null) { foreach (string s in command.deletetriggersingroup) { string deleteTriggerGroup = s.NullSafeTrim(); if (!String.IsNullOrEmpty(deleteTriggerGroup)) { triggerGroupsToDelete.Add(deleteTriggerGroup); } } } if (command.deletejob != null) { foreach (preprocessingcommandsTypeDeletejob s in command.deletejob) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified."); } jobsToDelete.Add(new JobKey(name, group)); } } if (command.deletetrigger != null) { foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified."); } triggersToDelete.Add(new TriggerKey(name, group)); } } } } if (log.IsDebugEnabled) { log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands."); log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands."); log.Debug("Found " + jobsToDelete.Count + " delete job commands."); log.Debug("Found " + triggersToDelete.Count + " delete trigger commands."); } // // Extract directives // if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool overWrite = data.processingdirectives[0].overwriteexistingdata; log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite); OverWriteExistingData = overWrite; } else { log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData); } if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates; log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates); IgnoreDuplicates = ignoreduplicates; } else { log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates); } if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger; log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative); ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative; } else { log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger); } // // Extract Job definitions... // List <jobdetailType> jobNodes = new List <jobdetailType>(); if (data.schedule != null) { foreach (var schedule in data.schedule) { if (schedule != null) { if (schedule.job != null) { jobNodes.AddRange(schedule.job); } } } } log.Debug("Found " + jobNodes.Count + " job definitions."); foreach (jobdetailType jobDetailType in jobNodes) { string jobName = jobDetailType.name.TrimEmptyToNull(); string jobGroup = jobDetailType.group.TrimEmptyToNull(); string jobDescription = jobDetailType.description.TrimEmptyToNull(); string jobTypeName = jobDetailType.jobtype.TrimEmptyToNull(); bool jobDurability = jobDetailType.durable; bool jobRecoveryRequested = jobDetailType.recover; Type jobType = typeLoadHelper.LoadType(jobTypeName); IJobDetail jobDetail = JobBuilder.Create(jobType) .WithIdentity(jobName, jobGroup) .WithDescription(jobDescription) .StoreDurably(jobDurability) .RequestRecovery(jobRecoveryRequested) .Build(); if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null) { foreach (entryType entry in jobDetailType.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); jobDetail.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled) { log.Debug("Parsed job definition: " + jobDetail); } AddJobToSchedule(jobDetail); } // // Extract Trigger definitions... // List <triggerType> triggerEntries = new List <triggerType>(); if (data.schedule != null) { foreach (var schedule in data.schedule) { if (schedule != null && schedule.trigger != null) { triggerEntries.AddRange(schedule.trigger); } } } log.Debug("Found " + triggerEntries.Count + " trigger definitions."); foreach (triggerType triggerNode in triggerEntries) { string triggerName = triggerNode.Item.name.TrimEmptyToNull(); string triggerGroup = triggerNode.Item.group.TrimEmptyToNull(); string triggerDescription = triggerNode.Item.description.TrimEmptyToNull(); string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull(); string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull(); string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull(); int triggerPriority = TriggerConstants.DefaultPriority; if (!triggerNode.Item.priority.IsNullOrWhiteSpace()) { triggerPriority = Convert.ToInt32(triggerNode.Item.priority); } DateTimeOffset triggerStartTime = SystemTime.UtcNow(); if (triggerNode.Item.Item != null) { if (triggerNode.Item.Item is DateTime) { triggerStartTime = new DateTimeOffset((DateTime)triggerNode.Item.Item); } else { triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item)); } } DateTime?triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?)null; IScheduleBuilder sched; if (triggerNode.Item is simpleTriggerType) { simpleTriggerType simpleTrigger = (simpleTriggerType)triggerNode.Item; string repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull(); string repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull(); int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString); TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString)); sched = SimpleScheduleBuilder.Create() .WithInterval(repeatInterval) .WithRepeatCount(repeatCount); if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((SimpleScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction)); } } else if (triggerNode.Item is cronTriggerType) { cronTriggerType cronTrigger = (cronTriggerType)triggerNode.Item; string cronExpression = cronTrigger.cronexpression.TrimEmptyToNull(); string timezoneString = cronTrigger.timezone.TrimEmptyToNull(); TimeZoneInfo tz = timezoneString != null?TimeZoneInfo.FindSystemTimeZoneById(timezoneString) : null; sched = CronScheduleBuilder.CronSchedule(cronExpression) .InTimeZone(tz); if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CronScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction)); } } else if (triggerNode.Item is calendarIntervalTriggerType) { calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType)triggerNode.Item; string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull(); IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull()); int repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString); sched = CalendarIntervalScheduleBuilder.Create() .WithInterval(repeatInterval, intervalUnit); if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CalendarIntervalScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction)); } } else { throw new SchedulerConfigException("Unknown trigger type in XML configuration"); } IMutableTrigger trigger = (IMutableTrigger)TriggerBuilder.Create() .WithIdentity(triggerName, triggerGroup) .WithDescription(triggerDescription) .ForJob(triggerJobName, triggerJobGroup) .StartAt(triggerStartTime) .EndAt(triggerEndTime) .WithPriority(triggerPriority) .ModifiedByCalendar(triggerCalendarRef) .WithSchedule(sched) .Build(); if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null) { foreach (entryType entry in triggerNode.Item.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); trigger.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled) { log.Debug("Parsed trigger definition: " + trigger); } AddTriggerToSchedule(trigger); } }
private static void TestJob(string file) { Console.WriteLine("----------- 检测文件配置 START -------------"); #region 加载文件信息 var xml = File.ReadAllText(file); XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); List <jobdetailType> jobNodes = new List <jobdetailType>(); List <cronTriggerType> triggerTypes = new List <cronTriggerType>(); if (data.schedule != null) { foreach (jobschedulingdataSchedule schedule in data.schedule) { if (schedule?.job != null) { jobNodes.AddRange(schedule.job); } } foreach (jobschedulingdataSchedule schedule2 in data.schedule) { if (schedule2?.trigger != null) { foreach (var item in schedule2.trigger) { cronTriggerType cronTrigger = item.Item as cronTriggerType; if (cronTrigger == null) { continue; } triggerTypes.Add(cronTrigger); } } } } #endregion #region 检测 jobtype if (jobNodes.Count == 0) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] 没有可执行任务!"); } else { foreach (var node in jobNodes) { var type = Type.GetType(node.jobtype); if (type == null) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}]jobtype【{node.jobtype}】出错了..."); } else { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}]job【{node.name}】检测成功..."); } } } #endregion #region 检测 trigger if (triggerTypes.Count == 0) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] 没有配置trigger!"); } else { foreach (var node in triggerTypes) { const string reg = @"^(((([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?,)*([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?)|(([\*]|[0-9]|[0-5][0-9])/([0-9]|[0-5][0-9]))|([\?])|([\*]))[\s](((([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?,)*([0-9]|[0-5][0-9])(-([0-9]|[0-5][0-9]))?)|(([\*]|[0-9]|[0-5][0-9])/([0-9]|[0-5][0-9]))|([\?])|([\*]))[\s](((([0-9]|[0-1][0-9]|[2][0-3])(-([0-9]|[0-1][0-9]|[2][0-3]))?,)*([0-9]|[0-1][0-9]|[2][0-3])(-([0-9]|[0-1][0-9]|[2][0-3]))?)|(([\*]|[0-9]|[0-1][0-9]|[2][0-3])/([0-9]|[0-1][0-9]|[2][0-3]))|([\?])|([\*]))[\s](((([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(-([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]))?,)*([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(-([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1]))?(C)?)|(([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])/([1-9]|[0][1-9]|[1-2][0-9]|[3][0-1])(C)?)|(L(-[0-9])?)|(L(-[1-2][0-9])?)|(L(-[3][0-1])?)|(LW)|([1-9]W)|([1-3][0-9]W)|([\?])|([\*]))[\s](((([1-9]|0[1-9]|1[0-2])(-([1-9]|0[1-9]|1[0-2]))?,)*([1-9]|0[1-9]|1[0-2])(-([1-9]|0[1-9]|1[0-2]))?)|(([1-9]|0[1-9]|1[0-2])/([1-9]|0[1-9]|1[0-2]))|(((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?,)*(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?)|((JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)/(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))|([\?])|([\*]))[\s]((([1-7](-([1-7]))?,)*([1-7])(-([1-7]))?)|([1-7]/([1-7]))|(((MON|TUE|WED|THU|FRI|SAT|SUN)(-(MON|TUE|WED|THU|FRI|SAT|SUN))?,)*(MON|TUE|WED|THU|FRI|SAT|SUN)(-(MON|TUE|WED|THU|FRI|SAT|SUN))?(C)?)|((MON|TUE|WED|THU|FRI|SAT|SUN)/(MON|TUE|WED|THU|FRI|SAT|SUN)(C)?)|(([1-7]|(MON|TUE|WED|THU|FRI|SAT|SUN))?(L|LW)?)|(([1-7]|MON|TUE|WED|THU|FRI|SAT|SUN)#([1-7])?)|([\?])|([\*]))([\s]?(([\*])?|(19[7-9][0-9])|(20[0-9][0-9]))?| (((19[7-9][0-9])|(20[0-9][0-9]))/((19[7-9][0-9])|(20[0-9][0-9])))?| ((((19[7-9][0-9])|(20[0-9][0-9]))(-((19[7-9][0-9])|(20[0-9][0-9])))?,)*((19[7-9][0-9])|(20[0-9][0-9]))(-((19[7-9][0-9])|(20[0-9][0-9])))?)?)$"; var m = Regex.Match(node.cronexpression, reg); if (m.Success) { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}]trigger【{node.name}】检测成功..."); } else { Console.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}]trigger【{node.name}】出错了..."); } } } #endregion Console.WriteLine("----------- 检测文件配置 END -------------"); }
public static List <JobInfo> GetJobInfos(string file) { List <JobInfo> jobInfos = new List <JobInfo>(); if (System.IO.File.Exists(file) == false) { return(jobInfos); } var xmlFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(file), "quartz_jobs.xml"); if (System.IO.File.Exists(xmlFile) == false) { return(jobInfos); } var xml = System.IO.File.ReadAllText(xmlFile); XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); List <jobdetailType> jobNodes = new List <jobdetailType>(); if (data.schedule != null) { foreach (jobschedulingdataSchedule schedule in data.schedule) { if (((schedule != null) ? schedule.job : null) != null) { jobNodes.AddRange(schedule.job); } } } List <triggerType> triggerEntries = new List <triggerType>(); if (data.schedule != null) { foreach (jobschedulingdataSchedule schedule2 in data.schedule) { if (schedule2 != null && schedule2.trigger != null) { triggerEntries.AddRange(schedule2.trigger); } } } foreach (var item in jobNodes) { var list = triggerEntries.Where(q => q.Item.jobgroup == item.group && q.Item.jobname == item.name).ToList(); foreach (var trigger in list) { if (trigger.Item is cronTriggerType) { cronTriggerType cronTrigger = (cronTriggerType)trigger.Item; string cronExpression = cronTrigger.cronexpression.Trim(); if (CronExpression.IsValidExpression(cronExpression) == false) { } else { var cron = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cronExpression, new CronExpressionDescriptor.Options() { DayOfWeekStartIndexZero = false, Use24HourTimeFormat = true, }); jobInfos.Add(new JobInfo() { Name = item.name, TriggerName = cronTrigger.name, TriggerGroup = cronTrigger.group, Description = item.description, CronExpressionDescriptor = cron, Cron = cronExpression, NextStartTime = GetTaskeFireTime(cronExpression, 1)[0] }); } } } } return(jobInfos); }
public static bool SaveJob(string serviceName, string jobName, string description, string triggerGroup, string triggerName, string cron, out string msg) { //if (Session[SessionAdmin] == null) return Json(new { code = 0, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg = "请登录!" }, JsonRequestBehavior.AllowGet); description = description.Trim(); if (string.IsNullOrWhiteSpace(description)) { msg = "Job名称不能为空"; return(false); } cron = cron.Trim(); #region 判断Cron表达式 if (CronExpression.IsValidExpression(cron) == false) { msg = "Cron表达式错误"; return(false); } else { try { CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron, new CronExpressionDescriptor.Options() { DayOfWeekStartIndexZero = false, Use24HourTimeFormat = true, }); GetTaskeFireTime(cron, 1); } catch (Exception) { msg = "Cron表达式错误"; return(false); } } #endregion #region 务判断 var info = GetServiceInfo(serviceName, false, false); if (info == null) { msg = $"服务【{serviceName}】不存在!"; return(false); } #endregion #region 文件判断 var xmlFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(info.Path), "quartz_jobs.xml"); if (System.IO.File.Exists(xmlFile) == false) { msg = $"服务【{serviceName}】配置文件不存在!"; return(false); } #endregion #region 保存数据 var xml = System.IO.File.ReadAllText(xmlFile); XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); if (data.schedule != null) { foreach (jobschedulingdataSchedule schedule in data.schedule) { if (((schedule != null) ? schedule.job : null) != null) { foreach (var item in schedule.job) { if (item.name == jobName) { item.description = description; } } } } foreach (jobschedulingdataSchedule schedule2 in data.schedule) { if (schedule2 != null && schedule2.trigger != null) { foreach (var item in schedule2.trigger) { cronTriggerType cronTrigger = item.Item as cronTriggerType; if (cronTrigger == null) { continue; } if (cronTrigger.group == triggerGroup && cronTrigger.name == triggerName) { cronTrigger.cronexpression = cron; } } } } } #endregion #region 保存文件 xml = Serializer(typeof(QuartzXmlConfiguration20), data); System.IO.File.Copy(xmlFile, xmlFile + DateTime.Now.ToString("_yyyyMMdd_HHmmss") + ".bak", true); System.IO.File.WriteAllText(xmlFile, xml); #endregion msg = $"操作成功,请注意重启!"; return(true); }
public static int GetJob(string file, string jobName) { if (System.IO.File.Exists(file) == false) { return(0); } var xmlFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(file), "quartz_jobs.xml"); if (System.IO.File.Exists(xmlFile) == false) { return(0); } var xml = System.IO.File.ReadAllText(xmlFile); XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); List <jobdetailType> jobNodes = new List <jobdetailType>(); if (data.schedule != null) { foreach (jobschedulingdataSchedule schedule in data.schedule) { if (((schedule != null) ? schedule.job : null) != null) { jobNodes.AddRange(schedule.job); } } } var node = jobNodes.FirstOrDefault(q => q.name.ToLower() == jobName.ToLower()); if (node == null) { return(0); } List <triggerType> triggerEntries = new List <triggerType>(); if (data.schedule != null) { foreach (jobschedulingdataSchedule schedule2 in data.schedule) { if (schedule2 != null && schedule2.trigger != null) { triggerEntries.AddRange(schedule2.trigger); } } } var list = triggerEntries.Where(q => q.Item.jobgroup == node.group && q.Item.jobname == node.name).ToList(); foreach (var trigger in list) { if (trigger.Item is cronTriggerType) { cronTriggerType cronTrigger = (cronTriggerType)trigger.Item; string cronExpression = cronTrigger.cronexpression.Trim(); if (CronExpression.IsValidExpression(cronExpression) == false) { } else { if (RunJobLately(cronExpression)) { return(2); } } } } return(1); }