/// <summary> /// Create the job detail /// </summary> private void CreateJob() { this.jobDetail = JobBuilder.Create<HelloWorldJob>() .WithIdentity(jobKey) .Build(); this.jobDetail.JobDataMap.Put("DataKey", workerConfig.DataValue); }
public void JobAdded(IJobDetail jobDetail) { foreach (ISchedulerListener listener in listeners) { listener.JobAdded(jobDetail); } }
void AssignDataMap(IJobDetail jobDetail, object createObject) { if (jobDetail.JobDataMap!= null) { var typeInfo = TypesInfo.FindTypeInfo(createObject.GetType()); var jobDataMap = ((JobDataMap) jobDetail.JobDataMap); jobDataMap.Keys.OfType<string>().Each(AssignValue(createObject, jobDataMap, typeInfo)); } }
public static void ScheduleJob(this IScheduler scheduler, IJobDetail jobDetail, string scheduleText, TimeZoneInfo timeZone) { TextToScheduleFactory factory = new TextToScheduleFactory(); var english = factory.CreateEnglishParser(); var results = english.Parse(scheduleText, timeZone); results.ScheduleWithJob(scheduler, jobDetail); }
public void Initialize() { _job = CreateJob(); _trigger1 = CreateTrigger("trigger1", "triggerGroup1", _job.Key); _trigger2 = CreateTrigger("trigger2", "triggerGroup1", _job.Key); JobStore.StoreJob(_job, false); JobStore.StoreTrigger(_trigger1, false); JobStore.StoreTrigger(_trigger2, false); }
public JsonJob(IJobDetail jobDetail, IList<ITrigger> triggers) { JobType = jobDetail.JobType.FullName; Description = jobDetail.Description; Triggers = new List<JsonTrigger>(triggers.Count); foreach (var trigger in triggers) { Triggers.Add(new JsonTrigger(trigger)); } }
public JobDetailDto(IJobDetail jobDetail) { Durable = jobDetail.Durable; ConcurrentExecutionDisallowed = jobDetail.ConcurrentExecutionDisallowed; Description = jobDetail.Description; JobType = jobDetail.JobType.AssemblyQualifiedNameWithoutVersion(); Name = jobDetail.Key.Name; Group = jobDetail.Key.Group; PersistJobDataAfterExecution = jobDetail.PersistJobDataAfterExecution; RequestsRecovery = jobDetail.RequestsRecovery; }
public void StartUpdating() { if (State == RunningState.Waiting || State == RunningState.Stopped) { trigger = new SimpleTriggerImpl("Feed parsing", null, DateTime.Now, null, SimpleTriggerImpl.RepeatIndefinitely, RepeatInterval); jobDetail = new JobDetailImpl("job", typeof(UpdateJob)); jobDetail.JobDataMap["service"] = service; sched.ScheduleJob(jobDetail, trigger); State = RunningState.Runing; } }
private static void CreateJob() { // The job builder uses a fluent interface to // make it easier to build and generate an // IJobDetail object _pollingJobDetail = JobBuilder.Create<PollWebsiteJob>() .WithIdentity("StartPolling") // Here we can assign a friendly name to our job .Build(); // And now we build the job detail // Put options into data map _pollingJobDetail.JobDataMap.Put("Url", _options.Url); }
public int InsertExtendedTriggerProperties(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail) { ICronTrigger cronTrigger = (ICronTrigger) trigger; using (IDbCommand cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlInsertCronTrigger, TablePrefix, SchedNameLiteral))) { DbAccessor.AddCommandParameter(cmd, "triggerName", trigger.Key.Name); DbAccessor.AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); DbAccessor.AddCommandParameter(cmd, "triggerCronExpression", cronTrigger.CronExpressionString); DbAccessor.AddCommandParameter(cmd, "triggerTimeZone", cronTrigger.TimeZone.Id); return cmd.ExecuteNonQuery(); } }
public int InsertExtendedTriggerProperties(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail) { ISimpleTrigger simpleTrigger = (ISimpleTrigger) trigger; using (IDbCommand cmd = commandAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlInsertSimpleTrigger, tablePrefix, schedNameLiteral))) { commandAccessor.AddCommandParameter(cmd, "triggerName", trigger.Key.Name); commandAccessor.AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); commandAccessor.AddCommandParameter(cmd, "triggerRepeatCount", simpleTrigger.RepeatCount); commandAccessor.AddCommandParameter(cmd, "triggerRepeatInterval", simpleTrigger.RepeatInterval.TotalMilliseconds); commandAccessor.AddCommandParameter(cmd, "triggerTimesTriggered", simpleTrigger.TimesTriggered); return cmd.ExecuteNonQuery(); } }
/// <summary> /// Initializes a new instance of the <see cref="TriggerFiredBundle"/> class. /// </summary> /// <param name="job">The job.</param> /// <param name="trigger">The trigger.</param> /// <param name="cal">The calendar.</param> /// <param name="jobIsRecovering">if set to <c>true</c> [job is recovering].</param> /// <param name="fireTimeUtc">The fire time.</param> /// <param name="scheduledFireTimeUtc">The scheduled fire time.</param> /// <param name="prevFireTimeUtc">The previous fire time.</param> /// <param name="nextFireTimeUtc">The next fire time.</param> public TriggerFiredBundle(IJobDetail job, IOperableTrigger trigger, ICalendar cal, bool jobIsRecovering, DateTimeOffset? fireTimeUtc, DateTimeOffset? scheduledFireTimeUtc, DateTimeOffset? prevFireTimeUtc, DateTimeOffset? nextFireTimeUtc) { this.job = job; this.trigger = trigger; this.cal = cal; this.jobIsRecovering = jobIsRecovering; this.fireTimeUtc = fireTimeUtc; this.scheduledFireTimeUtc = scheduledFireTimeUtc; this.prevFireTimeUtc = prevFireTimeUtc; this.nextFireTimeUtc = nextFireTimeUtc; }
public static void Start() { IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); //int Hr = Convert.ToInt32(ConfigurationManager.AppSettings["ScheduleHour"]); //int Mn = Convert.ToInt32(ConfigurationManager.AppSettings["ScheduleMinute"]); //IJobDetail job = JobBuilder.Create<PackingSummaryEmailJob>().Build(); //ITrigger trigger = TriggerBuilder.Create() // .WithDailyTimeIntervalSchedule // (s => // s.WithIntervalInHours(24) // .OnEveryDay() // .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(Hr, Mn)) // ) // .Build(); //For Weekly Reports Create New Job & Trigger int WeeklyDay = Convert.ToInt32(ConfigurationManager.AppSettings["WeeklyScheduleDay"]); int WeeklyTimeHour = Convert.ToInt32(ConfigurationManager.AppSettings["WeeklyScheduleTimeHour"]); int WeeklyTimeMinut = Convert.ToInt32(ConfigurationManager.AppSettings["WeeklyScheduleTimeMinut"]); IJobDetail WeeklyJob = JobBuilder.Create <WeeklyEmailJob>().Build(); ITrigger Weeklytrigger = TriggerBuilder.Create() .WithSchedule(CronScheduleBuilder .WeeklyOnDayAndHourAndMinute((DayOfWeek)WeeklyDay, WeeklyTimeHour, WeeklyTimeMinut) .InTimeZone(TimeZoneInfo.Local)) .Build(); //For Monthly Reports Create New Job & Trigger int MonthlyTime = Convert.ToInt32(ConfigurationManager.AppSettings["MonthlyScheduleTime"]); IJobDetail MonthlyJob = JobBuilder.Create <MonthlyEmailJob>().Build(); ITrigger Monthlytrigger = TriggerBuilder.Create() .WithSchedule(CronScheduleBuilder .MonthlyOnDayAndHourAndMinute(DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month), MonthlyTime, 15) .InTimeZone(TimeZoneInfo.Local)) .Build(); //For Daily Notification Create New Job & Trigger int NotificationHr = Convert.ToInt32(ConfigurationManager.AppSettings["DailyNotificationTime"]); IJobDetail DailyNotificationjob = JobBuilder.Create <DailyNotificationJob>().Build(); ITrigger DailyNotificationtrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(NotificationHr, 00)) ) .Build(); //For Daily Mail Create New Job & Trigger int DailyHours = Convert.ToInt32(ConfigurationManager.AppSettings["DailyScheduleHours"]); int DailyMinuts = Convert.ToInt32(ConfigurationManager.AppSettings["DailyScheduleMinut"]); IJobDetail Dailyjob = JobBuilder.Create <DailyEmailJob>().Build(); ITrigger Dailytrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(DailyHours, DailyMinuts)) ) .Build(); //For Daily Noon Mail Create New Job & Trigger int DailyNoonHours = Convert.ToInt32(ConfigurationManager.AppSettings["DailyNoonHours"]); int DailyNoonMinuts = Convert.ToInt32(ConfigurationManager.AppSettings["DailyNoonMinut"]); IJobDetail DailyNoonjob = JobBuilder.Create <DailyNoonEmailJob>().Build(); ITrigger DailyNoontrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(DailyNoonHours, DailyNoonMinuts)) ) .Build(); //For Daily Evening Mail Create New Job & Trigger int DailyEveningHours = Convert.ToInt32(ConfigurationManager.AppSettings["DailyEveningHours"]); int DailyEveningMinuts = Convert.ToInt32(ConfigurationManager.AppSettings["DailyEveningMinut"]); IJobDetail DailyEveningjob = JobBuilder.Create <DailyEveningEmailJob>().Build(); ITrigger DailyEveningtrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(DailyEveningHours, DailyEveningMinuts)) ) .Build(); //For Daily Night Mail Create New Job & Trigger int DailyNightHours = Convert.ToInt32(ConfigurationManager.AppSettings["DailyNightHours"]); int DailyNightMinuts = Convert.ToInt32(ConfigurationManager.AppSettings["DailyNightMinut"]); IJobDetail DailyNightjob = JobBuilder.Create <DailyNightEmailJob>().Build(); ITrigger DailyNighttrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(DailyNightHours, DailyNightMinuts)) ) .Build(); //For Daily Night Data Execution New Job & Trigger IJobDetail DailyNightDataExecutionjob = JobBuilder.Create <DailyNightDataExecutionJob>().Build(); ITrigger DailyNightDataExecutiontrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(DailyNightHours, DailyNightMinuts)) ) .Build(); //scheduler.ScheduleJob(job, trigger); scheduler.ScheduleJob(WeeklyJob, Weeklytrigger); scheduler.ScheduleJob(MonthlyJob, Monthlytrigger); scheduler.ScheduleJob(DailyNotificationjob, DailyNotificationtrigger); scheduler.ScheduleJob(Dailyjob, Dailytrigger); scheduler.ScheduleJob(DailyNoonjob, DailyNoontrigger); scheduler.ScheduleJob(DailyEveningjob, DailyEveningtrigger); scheduler.ScheduleJob(DailyNightjob, DailyNighttrigger); scheduler.ScheduleJob(DailyNightDataExecutionjob, DailyNightDataExecutiontrigger); }
public NativeJobDetailDisplay(IJobDetail detail) : this() { mDetail = detail; }
protected virtual void AddJobToSchedule(IJobDetail job) { loadedJobs.Add(job); }
protected internal void NotifyJobStoreJobVetoed(IOperableTrigger trigger, IJobDetail detail, SchedulerInstruction instCode) { resources.JobStore.TriggeredJobComplete(trigger, detail, instCode); }
public virtual async Task Run(bool inClearJobs, bool inScheduleJobs) { NameValueCollection properties = new NameValueCollection { ["quartz.scheduler.instanceName"] = "TestScheduler", ["quartz.scheduler.instanceId"] = "instance_one", ["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz", ["quartz.threadPool.threadCount"] = "5", ["quartz.jobStore.misfireThreshold"] = "60000", ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz", ["quartz.jobStore.useProperties"] = "false", ["quartz.jobStore.dataSource"] = "default", ["quartz.jobStore.tablePrefix"] = "QRTZ_", ["quartz.jobStore.clustered"] = "true", ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz", ["quartz.dataSource.default.connectionString"] = "Server=(local);Database=quartz;Trusted_Connection=True;", ["quartz.dataSource.default.provider"] = "SqlServer-20", ["quartz.serializer.type"] = "json" }; // if running SQLite we need this // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz"; #if NETSTANDARD_DBPROVIDERS properties["quartz.dataSource.default.provider"] = "SqlServer-41"; #else #endif // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = await sf.GetScheduler(); if (inClearJobs) { log.Warn("***** Deleting existing jobs/triggers *****"); await sched.Clear(); } log.Info("------- Initialization Complete -----------"); if (inScheduleJobs) { log.Info("------- Scheduling Jobs ------------------"); string schedId = sched.SchedulerInstanceId; int count = 1; IJobDetail job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); log.InfoFormat("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds); count++; job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(2, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create <SimpleRecoveryStatefulJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(3))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(4))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromMilliseconds(4500))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}"); await sched.ScheduleJob(job, trigger); } // jobs don't start firing until start() has been called... log.Info("------- Starting Scheduler ---------------"); await sched.Start(); log.Info("------- Started Scheduler ----------------"); log.Info("------- Waiting for one hour... ----------"); await Task.Delay(TimeSpan.FromHours(1)); log.Info("------- Shutting Down --------------------"); await sched.Shutdown(); log.Info("------- Shutdown Complete ----------------"); }
public virtual async Task Run() { ILog log = LogProvider.GetLogger(typeof(CronTriggerExample)); log.Info("------- Initializing -------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = await sf.GetScheduler(); log.Info("------- Initialization Complete --------"); log.Info("------- Scheduling Jobs ----------------"); // jobs can be scheduled before sched.start() has been called // job 1 will run every 20 seconds IJobDetail job = JobBuilder.Create <SimpleJob>() .WithIdentity("job1", "group1") .Build(); ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .WithCronSchedule("0/20 * * * * ?") .Build(); DateTimeOffset ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); // job 2 will run every other minute (at 15 seconds past the minute) job = JobBuilder.Create <SimpleJob>() .WithIdentity("job2", "group1") .Build(); trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .WithCronSchedule("15 0/2 * * * ?") .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); // job 3 will run every other minute but only between 8am and 5pm job = JobBuilder.Create <SimpleJob>() .WithIdentity("job3", "group1") .Build(); trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .WithCronSchedule("0 0/2 8-17 * * ?") .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); // job 4 will run every three minutes but only between 5pm and 11pm job = JobBuilder.Create <SimpleJob>() .WithIdentity("job4", "group1") .Build(); trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger4", "group1") .WithCronSchedule("0 0/3 17-23 * * ?") .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); // job 5 will run at 10am on the 1st and 15th days of the month job = JobBuilder.Create <SimpleJob>() .WithIdentity("job5", "group1") .Build(); trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger5", "group1") .WithCronSchedule("0 0 10am 1,15 * ?") .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); // job 6 will run every 30 seconds but only on Weekdays (Monday through Friday) job = JobBuilder.Create <SimpleJob>() .WithIdentity("job6", "group1") .Build(); trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger6", "group1") .WithCronSchedule("0,30 * * ? * MON-FRI") .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); // job 7 will run every 30 seconds but only on Weekends (Saturday and Sunday) job = JobBuilder.Create <SimpleJob>() .WithIdentity("job7", "group1") .Build(); trigger = (ICronTrigger)TriggerBuilder.Create() .WithIdentity("trigger7", "group1") .WithCronSchedule("0,30 * * ? * SAT,SUN") .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " has been scheduled to run at: " + ft + " and repeat based on expression: " + trigger.CronExpressionString); log.Info("------- Starting Scheduler ----------------"); // All of the jobs have been added to the scheduler, but none of the // jobs // will run until the scheduler has been started await sched.Start(); log.Info("------- Started Scheduler -----------------"); log.Info("------- Waiting five minutes... ------------"); // wait five minutes to show jobs await Task.Delay(TimeSpan.FromMinutes(5)); // executing... log.Info("------- Shutting Down ---------------------"); await sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = await sched.GetMetaData(); log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs."); }
public static void SetJobData(this IJobDetail jobDetail, JobDataModel jobData) { jobDetail.JobDataMap.Put(DataMapKeys.DataHashCode, jobData.GetDataHashCode()); jobDetail.JobDataMap.Put(DataMapKeys.SdkVersion, jobData.SdkVersion); jobDetail.JobDataMap.Put(DataMapKeys.Settings, jobData.Settings); }
public Task JobAdded(IJobDetail jobDetail, CancellationToken cancellationToken = default) { _logger.LogInformation($"Job Added:{jobDetail.Key}"); return(Task.CompletedTask); }
/// <summary> /// Starts the job scheduler. /// </summary> public void StartJobScheduler() { if (!System.IO.File.Exists("web.connectionstrings.config")) { // Write an eventlog about web.connectionstring.config not found this.EventLog.WriteEntry("Unable to find web.connectionstrings.config", EventLogEntryType.Error); } ISchedulerFactory sf; // create scheduler sf = new StdSchedulerFactory(); sched = sf.GetScheduler(); var rockContext = new RockContext(); // get list of active jobs ServiceJobService jobService = new ServiceJobService(rockContext); List <ServiceJob> activeJobs = null; try { // make sure that we can connect to the database and get the jobs list. Write a good EventLog message and exit the app if we can't this.EventLog.WriteEntry(string.Format("Connecting to database {0}:{1}", rockContext.Database.Connection.DataSource, rockContext.Database.Connection.Database), EventLogEntryType.Information); rockContext.Database.Connection.Open(); activeJobs = jobService.GetActiveJobs().ToList(); } catch (Exception ex) { this.EventLog.WriteEntry("Unable load active jobs list. " + ex.Message, EventLogEntryType.Error); throw ex; } foreach (ServiceJob job in activeJobs) { const string errorLoadingStatus = "Error Loading Job"; try { IJobDetail jobDetail = jobService.BuildQuartzJob(job); ITrigger jobTrigger = jobService.BuildQuartzTrigger(job); sched.ScheduleJob(jobDetail, jobTrigger); //// if the last status was an error, but we now loaded successful, clear the error // also, if the last status was 'Running', clear that status because it would have stopped if the app restarted if (job.LastStatus == errorLoadingStatus || job.LastStatus == "Running") { job.LastStatusMessage = string.Empty; job.LastStatus = string.Empty; rockContext.SaveChanges(); } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); // get path to the services directory string path = System.Reflection.Assembly.GetExecutingAssembly().Location; path = System.IO.Path.GetDirectoryName(path); // create the error message string message = string.Format("Error loading the job: {0}.\n\n{1}\n\n Job Assembly: {2}, Path: {3}", job.Name, ex.Message, job.Assembly, path); job.LastStatusMessage = message; job.LastStatus = errorLoadingStatus; rockContext.SaveChanges(); } // set up the listener to report back from jobs as they complete sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs()); // start the scheduler sched.Start(); } // set up the listener to report back from jobs as they complete sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs()); // start the scheduler sched.Start(); }
public async Task <IActionResult> Post(List <IFormFile> file) { List <CodeResponse> response = new List <CodeResponse>(); List <CodeResponse> existingCodeData = new List <CodeResponse>(); long size = file.Sum(f => f.Length); bool IsFileExists = false; string type, dirFullpath, nbPath, _url = string.Empty; // full path to file in temp location var filePath = Path.GetTempFileName(); foreach (var formFile in file) { dirFullpath = DirectoryHelper.GetCodeDirectoryPath(); #region type var fileExt = System.IO.Path.GetExtension(formFile.FileName).Substring(1); // upload file edn and start creating payload switch (fileExt.ToLower()) { case "py": type = "PYTHON"; break; case "ipynb": type = "JUPYTER_NOTEBOOK"; break; case "r": type = "R"; break; default: type = "UNRECOGNIZED"; break; } #endregion if (formFile.Length > 0) { //check if the file with the same name exists existingCodeData = CodePayload.Get(); if (existingCodeData.Count > 0) { // foreach (var record in existingCodeData) { if (record.Name == formFile.FileName) { IsFileExists = true; } } } existingCodeData.Clear(); // if (!FilePathHelper.IsFileNameValid(formFile.FileName)) { return(BadRequest("File name not valid.")); } if (!IsFileExists) { #region upload large file > 400MB if (size > 40000000) { Console.WriteLine(">>>>>>>>>>>>>>>>>>>>UPLOADING LARGE CODE FILE................................"); #region add to uploading // FilesInProgress wip = new FilesInProgress() { Id = formFile.FileName, CreatedAt = DateTime.Now, Name = formFile.FileName, Type = type, Module = "CODE", UploadStatus = "INPROGRESS" }; FilesUploadingPayload.Create(wip); #endregion //check if same job is scheduled ISchedulerFactory schfack = new StdSchedulerFactory(); IScheduler scheduler = await schfack.GetScheduler(); var jobKey = new JobKey(filePath); if (await scheduler.CheckExists(jobKey)) { await scheduler.ResumeJob(jobKey); } else { #region create quartz job for training model ITrigger trigger = TriggerBuilder.Create() .WithIdentity($"Uploading Code file-{DateTime.Now}") .WithPriority(1) .Build(); IJobDetail job = JobBuilder.Create <UploadJob>() .WithIdentity(filePath) .Build(); job.JobDataMap["id"] = formFile.FileName.Replace($".{fileExt}", ""); job.JobDataMap["filePath"] = filePath; await _scheduler.ScheduleJob(job, trigger); #endregion } } #endregion if (fileExt.ToLower() == "ipynb") { dirFullpath = dirFullpath + formFile.FileName.Replace(".ipynb", "/"); _url = DirectoryHelper.GetCodeUrl(formFile.FileName.Replace(".ipynb", string.Empty) + "/" + formFile.FileName); } else { _url = DirectoryHelper.GetCodeUrl(formFile.FileName); } nbPath = dirFullpath + formFile.FileName; //check if folder path exists...if not then create folder if (!Directory.Exists(dirFullpath)) { Directory.CreateDirectory(dirFullpath); } // upload file start using (var fileStream = new FileStream(Path.Combine(dirFullpath, formFile.FileName), FileMode.Create)) { //check file allowed extensions if (!extensions.Contains(fileExt.ToString().ToLower())) { return(BadRequest("File type not allowed")); } //file copy await formFile.CopyToAsync(fileStream); CodeResponse newRecord = new CodeResponse() { Id = formFile.FileName.Replace("." + fileExt, ""), Name = formFile.FileName, User = "", Created_on = DateTime.Now.ToString(), Edited_on = DateTime.Now.ToString(), Extension = fileExt, MimeType = formFile.ContentType, Size = formFile.Length, Type = type, Url = _url, FilePath = nbPath, DateCreated = DateTime.Now }; CodePayload.Create(newRecord); response.Add(newRecord); } } else { return(Conflict(new { message = "File already exists.", error = "File already exists." })); } } IsFileExists = false; } if (response.Count > 0) { return(Ok(response)); } else { return(BadRequest("File already exists.")); } }
public async Task <IActionResult> ExecutePyAsync(string id) { string zmkResponse = ""; string filePath = ""; string reqBody = ""; try { //read cron information from the request body using (var reader = new StreamReader(Request.Body)) { var body = reader.ReadToEnd(); reqBody = body.ToString(); } // foreach (var record in codeResponse) { if (record.Id.ToString() == id) { filePath = record.FilePath; break; } } // if (!string.IsNullOrEmpty(filePath)) { zmkResponse = await pyCompileClient.ExecutePy(filePath, ""); var jsonObj = JsonConvert.DeserializeObject <ExecuteCodeResponse>(zmkResponse); jsonObj.executedAt = DateTime.Now; List <ExecuteCodeResponse> tresp = new List <ExecuteCodeResponse>(); tresp.Add(jsonObj); JObject cronjson = JObject.Parse(reqBody); if (cronjson["recurrence"].ToString() == "REPEAT") { //check if same job is scheduled ISchedulerFactory schfack = new StdSchedulerFactory(); IScheduler scheduler = await schfack.GetScheduler(); var jobKey = new JobKey(filePath); if (await scheduler.CheckExists(jobKey)) { await scheduler.ResumeJob(jobKey); } else { #region create quartz job for execute code ITrigger trigger = TriggerBuilder.Create() .WithIdentity($"Execute Code Job-{DateTime.Now}") .WithCronSchedule(cronjson["cronExpression"].ToString()) .WithPriority(1) .Build(); IJobDetail job = JobBuilder.Create <ExecuteCodeJob>() .WithIdentity(filePath) .Build(); job.JobDataMap["id"] = id; job.JobDataMap["filePath"] = filePath; job.JobDataMap["baseurl"] = Configuration["PyServiceLocation:srvurl"]; await _scheduler.ScheduleJob(job, trigger); //add to scheduler payload SchedulerResponse schJob = new SchedulerResponse() { CreatedOn = DateTime.Now.ToString(), CronExpression = cronjson["cronExpression"].ToString(), DateCreated = DateTime.Now, EditedOn = DateTime.Now.ToString(), FilePath = filePath, Id = id, Name = id, Type = "PYTHON", Url = "", Recurrence = cronjson["recurrence"].ToString(), StartDate = (cronjson["startDate"] == null) ? "" : cronjson["startDate"].ToString(), //cronjson["startDate"].ToString(), StartTimeH = (cronjson["startTimeH"] == null) ? "" : cronjson["startTimeH"].ToString(), StartTimeM = (cronjson["startTimeM"] == null) ? "" : cronjson["startTimeM"].ToString(), // ZMKResponse = tresp.ToList<object>(), History = tresp.ToList <object>() }; SchedulerPayload.Create(schJob); #endregion } } else { //add history JArray jHist = new JArray(); foreach (var r in tresp) { jHist.Add(new JObject() { { "idforData", r.idforData }, { "status", r.status }, { "executedAt", r.executedAt } }); } //add to scheduler payload SchedulerResponse schJob = new SchedulerResponse() { CreatedOn = DateTime.Now.ToString(), CronExpression = "", DateCreated = DateTime.Now, EditedOn = DateTime.Now.ToString(), FilePath = filePath, Id = id, Name = id, Type = "PYTHON", Url = "", Recurrence = "ONE_TIME", StartDate = "", StartTimeH = "", StartTimeM = "", // ZMKResponse = tresp.ToList<object>(), Status = "", History = jHist.ToList <object>() }; SchedulerPayload.Create(schJob); } return(Json(jsonObj)); } else { return(BadRequest(new { message = "File execution failed." })); } } catch (Exception ex) { return(BadRequest(new { message = "File execution failed.", exception = ex.StackTrace })); } }
public Task JobAdded(IJobDetail jobDetail) { return(TaskUtil.CompletedTask); }
/// <summary> /// This method has to be implemented in order that starting of the thread causes the object's /// run method to be called in that separately executing thread. /// </summary> public virtual void Run() { qs.AddInternalSchedulerListener(this); try { IOperableTrigger trigger = (IOperableTrigger)jec.Trigger; IJobDetail jobDetail = jec.JobDetail; do { JobExecutionException jobExEx = null; IJob job = jec.JobInstance; try { Begin(); } catch (SchedulerException se) { qs.NotifySchedulerListenersError( string.Format(CultureInfo.InvariantCulture, "Error executing Job ({0}: couldn't begin execution.", jec.JobDetail.Key), se); break; } // notify job & trigger listeners... SchedulerInstruction instCode; try { if (!NotifyListenersBeginning(jec)) { break; } } catch (VetoedException) { try { instCode = trigger.ExecutionComplete(jec, null); try { qs.NotifyJobStoreJobVetoed(trigger, jobDetail, instCode); } catch (JobPersistenceException) { VetoedJobRetryLoop(trigger, jobDetail, instCode); } // Even if trigger got vetoed, we still needs to check to see if it's the trigger's finalized run or not. if (jec.Trigger.GetNextFireTimeUtc() == null) { qs.NotifySchedulerListenersFinalized(jec.Trigger); } Complete(true); } catch (SchedulerException se) { qs.NotifySchedulerListenersError( string.Format(CultureInfo.InvariantCulture, "Error during veto of Job ({0}: couldn't finalize execution.", jec.JobDetail.Key), se); } break; } DateTimeOffset startTime = SystemTime.UtcNow(); DateTimeOffset endTime; // Execute the job try { if (log.IsDebugEnabled) { log.Debug("Calling Execute on job " + jobDetail.Key); } job.Execute(jec); endTime = SystemTime.UtcNow(); } catch (JobExecutionException jee) { endTime = SystemTime.UtcNow(); jobExEx = jee; log.Info(string.Format(CultureInfo.InvariantCulture, "Job {0} threw a JobExecutionException: ", jobDetail.Key), jobExEx); } catch (Exception e) { endTime = SystemTime.UtcNow(); log.Error(string.Format(CultureInfo.InvariantCulture, "Job {0} threw an unhandled Exception: ", jobDetail.Key), e); SchedulerException se = new SchedulerException("Job threw an unhandled exception.", e); qs.NotifySchedulerListenersError( string.Format(CultureInfo.InvariantCulture, "Job ({0} threw an exception.", jec.JobDetail.Key), se); jobExEx = new JobExecutionException(se, false); } jec.JobRunTime = endTime - startTime; // notify all job listeners if (!NotifyJobListenersComplete(jec, jobExEx)) { break; } instCode = SchedulerInstruction.NoInstruction; // update the trigger try { instCode = trigger.ExecutionComplete(jec, jobExEx); if (log.IsDebugEnabled) { log.Debug(string.Format(CultureInfo.InvariantCulture, "Trigger instruction : {0}", instCode)); } } catch (Exception e) { // If this happens, there's a bug in the trigger... SchedulerException se = new SchedulerException("Trigger threw an unhandled exception.", e); qs.NotifySchedulerListenersError("Please report this error to the Quartz developers.", se); } // notify all trigger listeners if (!NotifyTriggerListenersComplete(jec, instCode)) { break; } // update job/trigger or re-Execute job if (instCode == SchedulerInstruction.ReExecuteJob) { if (log.IsDebugEnabled) { log.Debug("Rescheduling trigger to reexecute"); } jec.IncrementRefireCount(); try { Complete(false); } catch (SchedulerException se) { qs.NotifySchedulerListenersError( string.Format(CultureInfo.InvariantCulture, "Error executing Job ({0}: couldn't finalize execution.", jec.JobDetail.Key), se); } continue; } try { Complete(true); } catch (SchedulerException se) { qs.NotifySchedulerListenersError( string.Format(CultureInfo.InvariantCulture, "Error executing Job ({0}: couldn't finalize execution.", jec.JobDetail.Key), se); continue; } try { qs.NotifyJobStoreJobComplete(trigger, jobDetail, instCode); } catch (JobPersistenceException jpe) { qs.NotifySchedulerListenersError( string.Format(CultureInfo.InvariantCulture, "An error occured while marking executed job complete. job= '{0}'", jobDetail.Key), jpe); if (!CompleteTriggerRetryLoop(trigger, jobDetail, instCode)) { return; } } break; } while (true); } finally { qs.RemoveInternalSchedulerListener(this); if (jec != null && jec.JobInstance != null) { qs.JobFactory.ReturnJob(jec.JobInstance); } } }
public static string GetDataHashCode(this IJobDetail job) { return(job.TryToReadDataMapString(DataMapKeys.DataHashCode)); }
/// <summary> /// Add the <see cref="IJob" /> identified by the given /// <see cref="IJobDetail" /> to the Scheduler, and /// associate the given <see cref="ITrigger" /> with it. /// <para> /// If the given Trigger does not reference any <see cref="IJob" />, then it /// will be set to reference the Job passed with it into this method. /// </para> /// </summary> public virtual DateTimeOffset ScheduleJob(IJobDetail jobDetail, ITrigger trigger) { ValidateState(); if (jobDetail == null) { throw new SchedulerException("JobDetail cannot be null"); } if (trigger == null) { throw new SchedulerException("Trigger cannot be null"); } if (jobDetail.Key == null) { throw new SchedulerException("Job's key cannot be null"); } if (jobDetail.JobType == null) { throw new SchedulerException("Job's class cannot be null"); } IOperableTrigger trig = (IOperableTrigger) trigger; if (trigger.JobKey == null) { trig.JobKey = jobDetail.Key; } else if (!trigger.JobKey.Equals(jobDetail.Key)) { throw new SchedulerException("Trigger does not reference given job!"); } trig.Validate(); ICalendar cal = null; if (trigger.CalendarName != null) { cal = resources.JobStore.RetrieveCalendar(trigger.CalendarName); if (cal == null) { throw new SchedulerException(string.Format(CultureInfo.InvariantCulture, "Calendar not found: {0}", trigger.CalendarName)); } } DateTimeOffset? ft = trig.ComputeFirstFireTimeUtc(cal); if (!ft.HasValue) { var message = string.Format("Based on configured schedule, the given trigger '{0}' will never fire.", trigger.Key); throw new SchedulerException(message); } resources.JobStore.StoreJobAndTrigger(jobDetail, trig); NotifySchedulerListenersJobAdded(jobDetail); NotifySchedulerThread(trigger.GetNextFireTimeUtc()); NotifySchedulerListenersScheduled(trigger); return ft.Value; }
public static string GetSdkVersion(this IJobDetail job) { return(job.TryToReadDataMapString(DataMapKeys.SdkVersion)); }
public virtual void AddJob(IJobDetail jobDetail, bool replace, bool storeNonDurableWhileAwaitingScheduling) { ValidateState(); if (!storeNonDurableWhileAwaitingScheduling && !jobDetail.Durable) { throw new SchedulerException("Jobs added with no trigger must be durable."); } resources.JobStore.StoreJob(jobDetail, replace); NotifySchedulerThread(null); NotifySchedulerListenersJobAdded(jobDetail); }
protected virtual void TriggeredJobComplete(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, IJobDetail jobDetail, SchedulerInstruction triggerInstCode) { try { if (triggerInstCode == SchedulerInstruction.DeleteTrigger) { if (!trigger.GetNextFireTimeUtc().HasValue) { // double check for possible reschedule within job // execution, which would cancel the need to delete... TriggerStatus stat = Delegate.SelectTriggerStatus(conn, trigger.Key); if (stat != null && !stat.NextFireTimeUtc.HasValue) { RemoveTrigger(conn, trigger.Key); } } else { RemoveTrigger(conn, trigger.Key); SignalSchedulingChangeOnTxCompletion(null); } } else if (triggerInstCode == SchedulerInstruction.SetTriggerComplete) { Delegate.UpdateTriggerState(conn, trigger.Key, StateComplete); SignalSchedulingChangeOnTxCompletion(null); } else if (triggerInstCode == SchedulerInstruction.SetTriggerError) { Log.Info("Trigger " + trigger.Key + " set to ERROR state."); Delegate.UpdateTriggerState(conn, trigger.Key, StateError); SignalSchedulingChangeOnTxCompletion(null); } else if (triggerInstCode == SchedulerInstruction.SetAllJobTriggersComplete) { Delegate.UpdateTriggerStatesForJob(conn, trigger.JobKey, StateComplete); SignalSchedulingChangeOnTxCompletion(null); } else if (triggerInstCode == SchedulerInstruction.SetAllJobTriggersError) { Log.Info("All triggers of Job " + trigger.JobKey + " set to ERROR state."); Delegate.UpdateTriggerStatesForJob(conn, trigger.JobKey, StateError); SignalSchedulingChangeOnTxCompletion(null); } if (jobDetail.ConcurrentExecutionDisallowed) { Delegate.UpdateTriggerStatesForJobFromOtherState(conn, jobDetail.Key, StateWaiting, StateBlocked); Delegate.UpdateTriggerStatesForJobFromOtherState(conn, jobDetail.Key, StatePaused, StatePausedBlocked); SignalSchedulingChangeOnTxCompletion(null); } if (jobDetail.PersistJobDataAfterExecution) { try { if (jobDetail.JobDataMap.Dirty) { Delegate.UpdateJobData(conn, jobDetail); } } catch (IOException e) { throw new JobPersistenceException("Couldn't serialize job data: " + e.Message, e); } catch (Exception e) { throw new JobPersistenceException("Couldn't update job data: " + e.Message, e); } } } catch (Exception e) { throw new JobPersistenceException("Couldn't update trigger state(s): " + e.Message, e); } try { Delegate.DeleteFiredTrigger(conn, trigger.FireInstanceId); } catch (Exception e) { throw new JobPersistenceException("Couldn't delete fired trigger: " + e.Message, e); } }
public static IServiceCollection AddQuartzJobDetail(this IServiceCollection services, IJobDetail detail) { services.AddSingleton <IScheduleJob>(provider => new ScheduleJob(detail, new List <ITrigger>())); return(services); }
public static void StoreJob(this IScheduler scheduler, IJobDetail jobDetail) { scheduler.StoreJobCore((JobDetailImpl)jobDetail); }
/// <summary> /// Schedules the given sets of jobs and triggers. /// </summary> /// <param name="sched">The sched.</param> public virtual async Task ScheduleJobs(IScheduler sched) { List <IJobDetail> jobs = new List <IJobDetail>(LoadedJobs); List <ITrigger> triggers = new List <ITrigger>(LoadedTriggers); log.Info("Adding " + jobs.Count + " jobs, " + triggers.Count + " triggers."); IDictionary <JobKey, List <IMutableTrigger> > triggersByFQJobName = BuildTriggersByFQJobNameMap(triggers); // add each job, and it's associated triggers while (jobs.Count > 0) { // remove jobs as we handle them... IJobDetail detail = jobs[0]; jobs.Remove(detail); IJobDetail dupeJ = null; try { // The existing job could have been deleted, and Quartz API doesn't allow us to query this without // loading the job class, so use try/catch to handle it. dupeJ = await sched.GetJobDetail(detail.Key).ConfigureAwait(false); } catch (JobPersistenceException e) { if (e.InnerException is TypeLoadException && OverWriteExistingData) { // We are going to replace jobDetail anyway, so just delete it first. log.Info("Removing job: " + detail.Key); await sched.DeleteJob(detail.Key).ConfigureAwait(false); } else { throw; } } if (dupeJ != null) { if (!OverWriteExistingData && IgnoreDuplicates) { log.Info("Not overwriting existing job: " + dupeJ.Key); continue; // just ignore the entry } if (!OverWriteExistingData && !IgnoreDuplicates) { throw new ObjectAlreadyExistsException(detail); } } if (dupeJ != null) { log.Info("Replacing job: " + detail.Key); } else { log.Info("Adding job: " + detail.Key); } List <IMutableTrigger> triggersOfJob; triggersByFQJobName.TryGetValue(detail.Key, out triggersOfJob); if (!detail.Durable && (triggersOfJob == null || triggersOfJob.Count == 0)) { if (dupeJ == null) { throw new SchedulerException( "A new job defined without any triggers must be durable: " + detail.Key); } if ((dupeJ.Durable && (await sched.GetTriggersOfJob(detail.Key).ConfigureAwait(false)).Count == 0)) { throw new SchedulerException( "Can't change existing durable job without triggers to non-durable: " + detail.Key); } } if (dupeJ != null || detail.Durable) { if (triggersOfJob != null && triggersOfJob.Count > 0) { await sched.AddJob(detail, true, true).ConfigureAwait(false); // add the job regardless is durable or not b/c we have trigger to add } else { await sched.AddJob(detail, true, false).ConfigureAwait(false); // add the job only if a replacement or durable, else exception will throw! } } else { bool addJobWithFirstSchedule = true; // Add triggers related to the job... while (triggersOfJob.Count > 0) { IMutableTrigger trigger = triggersOfJob[0]; // remove triggers as we handle them... triggersOfJob.Remove(trigger); ITrigger dupeT = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); if (dupeT != null) { if (OverWriteExistingData) { if (log.IsDebugEnabled()) { log.DebugFormat("Rescheduling job: {0} with updated trigger: {1}", trigger.JobKey, trigger.Key); } } else if (IgnoreDuplicates) { log.Info("Not overwriting existing trigger: " + dupeT.Key); continue; // just ignore the trigger (and possibly job) } else { throw new ObjectAlreadyExistsException(trigger); } if (!dupeT.JobKey.Equals(trigger.JobKey)) { log.WarnFormat("Possibly duplicately named ({0}) triggers in jobs xml file! ", trigger.Key); } await DoRescheduleJob(sched, trigger, dupeT).ConfigureAwait(false); } else { if (log.IsDebugEnabled()) { log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key); } try { if (addJobWithFirstSchedule) { await sched.ScheduleJob(detail, trigger).ConfigureAwait(false); // add the job if it's not in yet... addJobWithFirstSchedule = false; } else { await sched.ScheduleJob(trigger).ConfigureAwait(false); } } catch (ObjectAlreadyExistsException) { if (log.IsDebugEnabled()) { log.DebugFormat("Adding trigger: {0} for job: {1} failed because the trigger already existed. " + "This is likely due to a race condition between multiple instances " + "in the cluster. Will try to reschedule instead.", trigger.Key, detail.Key); } // Let's try one more time as reschedule. var oldTrigger = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); await DoRescheduleJob(sched, trigger, oldTrigger).ConfigureAwait(false); } } } } } // add triggers that weren't associated with a new job... (those we already handled were removed above) foreach (IMutableTrigger trigger in triggers) { ITrigger dupeT = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); if (dupeT != null) { if (OverWriteExistingData) { if (log.IsDebugEnabled()) { log.DebugFormat("Rescheduling job: " + trigger.JobKey + " with updated trigger: " + trigger.Key); } } else if (IgnoreDuplicates) { log.Info("Not overwriting existing trigger: " + dupeT.Key); continue; // just ignore the trigger } else { throw new ObjectAlreadyExistsException(trigger); } if (!dupeT.JobKey.Equals(trigger.JobKey)) { log.WarnFormat("Possibly duplicately named ({0}) triggers in jobs xml file! ", trigger.Key); } await DoRescheduleJob(sched, trigger, dupeT).ConfigureAwait(false); } else { if (log.IsDebugEnabled()) { log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key); } try { await sched.ScheduleJob(trigger).ConfigureAwait(false); } catch (ObjectAlreadyExistsException) { if (log.IsDebugEnabled()) { log.Debug( "Adding trigger: " + trigger.Key + " for job: " + trigger.JobKey + " failed because the trigger already existed. " + "This is likely due to a race condition between multiple instances " + "in the cluster. Will try to reschedule instead."); } // Let's rescheduleJob one more time. var oldTrigger = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); await DoRescheduleJob(sched, trigger, oldTrigger).ConfigureAwait(false); } } } }
/// <summary> <para> /// Create a <see cref="ObjectAlreadyExistsException" /> and auto-generate a /// message using the name/group from the given <see cref="IJobDetail" />. /// </para> /// /// <para> /// The message will read: <br />"Unable to store Job with name: '__' and /// group: '__', because one already exists with this identification." /// </para> /// </summary> public ObjectAlreadyExistsException(IJobDetail offendingJob) : base($"Unable to store Job: '{offendingJob.Key}', because one already exists with this identification.") { }
protected virtual void ProcessInternal(string xml) { PrepForProcessing(); #if XML_SCHEMA ValidateXml(xml); #endif // XML_SCHEMA 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?TimeZoneUtil.FindTimeZoneById(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); } }
/// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual DateTimeOffset ScheduleJob(IJobDetail jobDetail, ITrigger trigger) { try { return GetRemoteScheduler().ScheduleJob(jobDetail, trigger); } catch (RemotingException re) { throw InvalidateHandleCreateException("Error communicating with remote scheduler.", re); } }
public async Task Run(ILog log) { log.Info("------- Initializing -------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete --------"); log.Info("------- Scheduling Jobs ----------------"); // get a "nice round" time a few seconds in the future.... DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 10); // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds IJobDetail job1 = JobBuilder.Create <ColorJob>() .WithIdentity("job1", "group1") .Build(); ISimpleTrigger trigger1 = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(4)) .Build(); // pass initialization parameters into the job job1.JobDataMap.Put(ColorJob.FavoriteColor, "Green"); job1.JobDataMap.Put(ColorJob.ExecutionCount, 1); // schedule the job to run DateTimeOffset scheduleTime1 = sched.ScheduleJob(job1, trigger1); log.Info($"{job1.Key} will run at: {scheduleTime1.ToString("r")} and repeat: {trigger1.RepeatCount} times, every {trigger1.RepeatInterval.TotalSeconds} seconds"); // job2 will also run 5 times, every 10 seconds IJobDetail job2 = JobBuilder.Create <ColorJob>() .WithIdentity("job2", "group1") .Build(); ISimpleTrigger trigger2 = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(4)) .Build(); // pass initialization parameters into the job // this job has a different favorite color! job2.JobDataMap.Put(ColorJob.FavoriteColor, "Red"); job2.JobDataMap.Put(ColorJob.ExecutionCount, 1); // schedule the job to run DateTimeOffset scheduleTime2 = sched.ScheduleJob(job2, trigger2); log.Info($"{job2.Key} will run at: {scheduleTime2.ToString("r")} and repeat: {trigger2.RepeatCount} times, every {trigger2.RepeatInterval.TotalSeconds} seconds"); log.Info("------- Starting Scheduler ----------------"); // All of the jobs have been added to the scheduler, but none of the jobs // will run until the scheduler has been started sched.Start(); log.Info("------- Started Scheduler -----------------"); log.Info("------- Waiting 60 seconds... -------------"); // wait five minutes to show jobs await Task.Delay(TimeSpan.FromMinutes(5)); // executing... log.Info("------- Shutting Down ---------------------"); sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = sched.GetMetaData(); log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs."); }
/// <summary> /// Store the given <see cref="IJob" />. /// </summary> /// <param name="newJob">The <see cref="IJob" /> to be stored.</param> /// <param name="replaceExisting">If <see langword="true" />, any <see cref="IJob" /> existing in the /// <see cref="IJobStore" /> with the same name and group should be /// over-written.</param> public virtual void StoreJob(IJobDetail newJob, bool replaceExisting) { bool repl = false; lock (lockObject) { if (this.CheckExists(newJob.Key)) { if (!replaceExisting) { throw new ObjectAlreadyExistsException(newJob); } repl = true; } if (!repl) { // try insert new this.Jobs.Insert(newJob.ToBsonDocument()); } else { // force upsert this.Jobs.Save(newJob.ToBsonDocument()); } } }
/// <summary> /// 一开始执行 /// </summary> public QuartzHelper() { Scheduler = Factory.GetScheduler(); Scheduler = Factory.GetScheduler(); Job = JobBuilder.Create <T>().Build(); }
/// <summary> /// Inform the <see cref="IJobStore" /> that the scheduler has completed the /// firing of the given <see cref="ITrigger" /> (and the execution its /// associated <see cref="IJob" />), and that the <see cref="JobDataMap" /> /// in the given <see cref="IJobDetail" /> should be updated if the <see cref="IJob" /> /// is stateful. /// </summary> public virtual void TriggeredJobComplete(IOperableTrigger trigger, IJobDetail jobDetail, SchedulerInstruction triggerInstCode) { lock (lockObject) { this.ReleaseAcquiredTrigger(trigger); // It's possible that the job is null if: // 1- it was deleted during execution // 2- RAMJobStore is being used only for volatile jobs / triggers // from the JDBC job store if (jobDetail.PersistJobDataAfterExecution) { this.Jobs.Update( Query.EQ("_id", jobDetail.Key.ToBsonDocument()), Update.Set("JobDataMap", jobDetail.JobDataMap.ToBsonDocument())); } if (jobDetail.ConcurrentExecutionDisallowed) { IList<Spi.IOperableTrigger> jobTriggers = this.GetTriggersForJob(jobDetail.Key); IEnumerable<BsonDocument> triggerKeys = jobTriggers.Select(t => t.Key.ToBsonDocument()); this.Triggers.Update( Query.And( Query.In("_id", triggerKeys), Query.EQ("State", "Blocked")), Update.Set("State", "Waiting")); this.Triggers.Update( Query.And( Query.In("_id", triggerKeys), Query.EQ("State", "PausedAndBlocked")), Update.Set("State", "Paused")); signaler.SignalSchedulingChange(null); } // even if it was deleted, there may be cleanup to do this.BlockedJobs.Remove( Query.EQ("_id", jobDetail.Key.ToBsonDocument())); // check for trigger deleted during execution... if (triggerInstCode == SchedulerInstruction.DeleteTrigger) { log.Debug("Deleting trigger"); DateTimeOffset? d = trigger.GetNextFireTimeUtc(); if (!d.HasValue) { // double check for possible reschedule within job // execution, which would cancel the need to delete... d = trigger.GetNextFireTimeUtc(); if (!d.HasValue) { this.RemoveTrigger(trigger.Key); } else { log.Debug("Deleting cancelled - trigger still active"); } } else { this.RemoveTrigger(trigger.Key); signaler.SignalSchedulingChange(null); } } else if (triggerInstCode == SchedulerInstruction.SetTriggerComplete) { this.Triggers.Update( Query.EQ("_id", trigger.Key.ToBsonDocument()), Update.Set("State", "Complete")); signaler.SignalSchedulingChange(null); } else if (triggerInstCode == SchedulerInstruction.SetTriggerError) { Log.Info(string.Format(CultureInfo.InvariantCulture, "Trigger {0} set to ERROR state.", trigger.Key)); this.Triggers.Update( Query.EQ("_id", trigger.Key.ToBsonDocument()), Update.Set("State", "Error")); signaler.SignalSchedulingChange(null); } else if (triggerInstCode == SchedulerInstruction.SetAllJobTriggersError) { Log.Info(string.Format(CultureInfo.InvariantCulture, "All triggers of Job {0} set to ERROR state.", trigger.JobKey)); IList<Spi.IOperableTrigger> jobTriggers = this.GetTriggersForJob(jobDetail.Key); IEnumerable<BsonDocument> triggerKeys = jobTriggers.Select(t => t.Key.ToBsonDocument()); this.Triggers.Update( Query.In("_id", triggerKeys), Update.Set("State", "Error")); signaler.SignalSchedulingChange(null); } else if (triggerInstCode == SchedulerInstruction.SetAllJobTriggersComplete) { IList<Spi.IOperableTrigger> jobTriggers = this.GetTriggersForJob(jobDetail.Key); IEnumerable<BsonDocument> triggerKeys = jobTriggers.Select(t => t.Key.ToBsonDocument()); this.Triggers.Update( Query.In("_id", triggerKeys), Update.Set("State", "Complete")); signaler.SignalSchedulingChange(null); } } }
public static TJobSettings GetSettings <TJobSettings>(this IJobDetail job) where TJobSettings : class { return(JobDataModel.DeserializeSettings <TJobSettings>(job.TryToReadDataMapString(DataMapKeys.Settings))); }
public async Task StoreJobAndTrigger(IJobDetail newJob, IOperableTrigger newTrigger, CancellationToken cancellationToken = default) { await StoreJob(newJob, true, cancellationToken).ConfigureAwait(false); await StoreTrigger(newTrigger, true, cancellationToken).ConfigureAwait(false); }
public virtual void JobAdded(IJobDetail jobDetail) { }
private static string TryToReadDataMapString(this IJobDetail job, string key) { return(job.JobDataMap.Keys.Contains(key) ? job.JobDataMap.GetString(key) : string.Empty); }
void updateJob(bool restart) { //init initSet(); if (restart) { if (!_scheduler.IsShutdown) { // _scheduler.DeleteJob(_upload_job.Key); jobflag("Wait Other Job to Complete.Please Wait.Thank Your."); _scheduler.Shutdown();//true _scheduler = StdSchedulerFactory.GetDefaultScheduler(); _scheduler.Start(); lbl0msg.Text = "Restart Success,and restart OK."; } } #region "upload" DateTimeOffset runTime = DateBuilder.EvenSecondDate(DateTimeOffset.Now); _upload_job = JobBuilder.Create<updateJob>() .WithIdentity("UploadJob", "UploadGroup") .Build(); _upload_trigger = TriggerBuilder.Create() .WithIdentity("UploadTrigger", "UploadGroup") .StartAt(runTime) .WithSimpleSchedule(x => x.WithIntervalInMinutes(_txt0Rtime).RepeatForever()) .Build(); // Tell quartz to schedule the job using our trigger _scheduler.ScheduleJob(_upload_job, _upload_trigger); #endregion "upload" }
public void JobAdded(IJobDetail jobDetail) { _log.Trace("Job {JobKey} added", jobDetail.Key); }
/// <summary> /// Calls the equivalent method on the 'proxied' <see cref="QuartzScheduler" />. /// </summary> public virtual void AddJob(IJobDetail jobDetail, bool replace) { try { GetRemoteScheduler().AddJob(jobDetail, replace); } catch (RemotingException re) { throw InvalidateHandleCreateException("Error communicating with remote scheduler.", re); } }
private static async Task RunProgramRunExample() { Alarm alarm1 = new Alarm() { NimId = "NIM1", Category = "operational" }; Alarm alarm2 = new Alarm() { NimId = "NIM2", Category = "operational" }; Alarm alarm3 = new Alarm() { NimId = "NIM3", Category = "service" }; AlarmRoute alarmRoute1 = new AlarmRoute() { Category = "service", CustomerID = -1, OrgId = 3, Id = "No1", Schedule = new AlarmSchedule() { Cron = "0 * * ? * FRI" }, Rules = new List <AlarmRouteRule>() { new AlarmRouteRule() { Id = 1, Destination = "Mr.Keert", Duration = 1, Fleet = 0, Repeat = 10 }, new AlarmRouteRule() { Id = 2, Destination = "Bergen", Duration = 10, Fleet = 0, Repeat = 1 }, new AlarmRouteRule() { Id = 3, Destination = "RS", Duration = 1, Fleet = 15, Repeat = 1 } } }; try { // Grab the Scheduler instance from the Factory NameValueCollection props = new NameValueCollection { { "quartz.serializer.type", "binary" }, { "quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" }, { "quartz.jobStore.tablePrefix", "QRTZ_" }, { "quartz.jobStore.dataSource", "quartzDatasource" }, { "quartz.dataSource.quartzDatasource.connectionString", @"Server=(localdb)\MSSQLLocalDB;Database=IntelinetTMSTest;Uid=quartz;Pwd=quartz123" }, { "quartz.dataSource.quartzDatasource.provider", "SqlServer" } }; StdSchedulerFactory factory = new StdSchedulerFactory(props); IScheduler scheduler = await factory.GetScheduler(); int counter = 0; List <JobKey> jobKeys = new List <JobKey>(); List <AlarmJobInfo> alarmJobInfoList = new List <AlarmJobInfo>(); foreach (AlarmRouteRule rule in alarmRoute1.Rules) { string groupname = "Route_rule_" + counter; IJobDetail job = JobBuilder.Create <AlarmAction>() .WithIdentity("AlarmRouteRule_" + rule.Id, groupname) .Build(); job.JobDataMap.Put("alarm", alarm1); job.JobDataMap.Put("rule", rule); ITrigger trigger = GetTrigger(groupname, rule, job); jobKeys.Add(new JobKey("AlarmRouteRule_" + rule.Id, groupname)); alarmJobInfoList.Add(new AlarmJobInfo() { Job = job, Trigger = trigger }); counter++; } JobChainingJobListener chain = new JobChainingJobListener("testChain"); for (int i = 1; i < jobKeys.Count; i++) { chain.AddJobChainLink(jobKeys[i - 1], jobKeys[i]); } scheduler.ListenerManager.AddJobListener(chain, GroupMatcher <JobKey> .AnyGroup()); for (int i = 0; i < alarmJobInfoList.Count - 1; i++) { IJobDetail j = alarmJobInfoList[i].Job; j.JobDataMap.Put("nextJob", alarmJobInfoList[i + 1].Job); j.JobDataMap.Put("nextTrigger", alarmJobInfoList[i + 1].Trigger); } // Tell quartz to schedule the job using our trigger await scheduler.ScheduleJob(alarmJobInfoList[0].Job, alarmJobInfoList[0].Trigger); // some sleep to show what's happening //await Task.Delay(TimeSpan.FromSeconds(30)); await scheduler.Start(); // and last shut down the scheduler when you are ready to close your program //await scheduler.Shutdown(); } catch (SchedulerException se) { Console.WriteLine(se); } }
public void JobAdded(IJobDetail jobDetail) { }
public void AddJob(KidsNoteScheduleParameters param) { var schedulerTask = StdSchedulerFactory.GetDefaultScheduler(); schedulerTask.Wait(); IScheduler scheduler = schedulerTask.Result; string jobName = param.ToString(); if (ActiveScheduleNames.Contains(jobName)) { return; } /* * 1.Seconds * 2.Minutes * 3.Hours * 4.Day - of - Month * 5.Month * 6.Day - of - Week * 7.Year(optional field) */ #if DEBUG DateTime scheduled = DateTime.Now; scheduled += new TimeSpan(0, 0, 0, 30); #endif string cronFormat = ""; if (param.Days == KidsNoteScheduleParameters.DaysType.MON_FRI) { #if DEBUG cronFormat = String.Format("{0} {1} {2} ? * MON-FRI", scheduled.Second, scheduled.Minute, scheduled.Hour); #else cronFormat = "0 0 * ? * MON-FRI"; #endif } else { #if DEBUG cronFormat = String.Format("{0} {1} {2} * * ?", scheduled.Second, scheduled.Minute, scheduled.Hour); #else cronFormat = "0 0 * * * ?"; #endif } IJobDetail job = JobBuilder.Create <KidsNoteScheduledJob>().WithIdentity(jobName, Constants.KISNOTE_SCHEDULER_GROUP_NAME).Build(); job.JobDataMap.Put("param", param); job.JobDataMap.Put("owner", this); ITrigger trigger = TriggerBuilder.Create() .WithIdentity(jobName, Constants.KISNOTE_SCHEDULER_GROUP_NAME) .WithCronSchedule(cronFormat) .ForJob(jobName, Constants.KISNOTE_SCHEDULER_GROUP_NAME) .Build(); scheduler.ScheduleJob(job, trigger); ActiveScheduleNames.Add(jobName); }
/// <summary> /// Store the given <see cref="IJobDetail" /> and <see cref="ITrigger" />. /// </summary> /// <param name="newJob">The <see cref="IJobDetail" /> to be stored.</param> /// <param name="newTrigger">The <see cref="ITrigger" /> to be stored.</param> public virtual void StoreJobAndTrigger(IJobDetail newJob, IOperableTrigger newTrigger) { StoreJob(newJob, false); StoreTrigger(newTrigger, false); }
public virtual async Task Run() { ILog log = LogProvider.GetLogger(typeof(JobExceptionExample)); log.Info("------- Initializing ----------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = await sf.GetScheduler(); log.Info("------- Initialization Complete ------------"); log.Info("------- Scheduling Jobs -------------------"); // jobs can be scheduled before start() has been called // get a "nice round" time a few seconds in the future... DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15); // badJob1 will run every 10 seconds // this job will throw an exception and refire // immediately IJobDetail job = JobBuilder.Create <BadJob1>() .WithIdentity("badJob1", "group1") .UsingJobData("denominator", "0") .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever()) .Build(); DateTimeOffset ft = await sched.ScheduleJob(job, trigger); log.Info(job.Key + " will run at: " + ft + " and repeat: " + trigger.RepeatCount + " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds"); // badJob2 will run every five seconds // this job will throw an exception and never // refire job = JobBuilder.Create <BadJob2>() .WithIdentity("badJob2", "group1") .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info($"{job.Key} will run at: {ft:r} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); log.Info("------- Starting Scheduler ----------------"); // jobs don't start firing until start() has been called... await sched.Start(); log.Info("------- Started Scheduler -----------------"); // sleep for 30 seconds await Task.Delay(TimeSpan.FromSeconds(30)); log.Info("------- Shutting Down ---------------------"); await sched.Shutdown(false); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = await sched.GetMetaData(); log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs."); }
public virtual void NotifySchedulerListenersJobAdded(IJobDetail jobDetail) { // notify all scheduler listeners foreach (ISchedulerListener listener in BuildSchedulerListenerList()) { try { listener.JobAdded(jobDetail); } catch (Exception e) { log.Error("Error while notifying SchedulerListener of JobAdded.", e); } } }
public async Task StartAsync() { await _gitHub.DownloadConfig(); var discordToken = _gitHub.Config.DiscordToken; // Get Discord token if (string.IsNullOrWhiteSpace(discordToken)) // Check if token is valid { throw new ArgumentNullException(discordToken); // Throw exception if token is invalid } while (true) { try { await Discord.LoginAsync(TokenType.Bot, discordToken); // Login to Discord await Discord.StartAsync(); // Connect to the websocket break; } catch (HttpException he) { await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Error, "Discord", he.Message)); await Task.Delay(TimeSpan.FromSeconds(10)); await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Warning, "Discord", "Trying to start again")); } catch (Exception e) { await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Critical, "Discord", e.Message, e)); // Log exception } } // Create datamap with required objects var defaultJobDataMap = new JobDataMap() { { "Client", Discord }, { "GitHub", _gitHub }, { "Logging", Logging }, { "Reddit", _reddit } }; // Create job for updating counters IJobDetail countersJob = JobBuilder.Create <UpdateCountersJob>() .WithIdentity("updateCountersJob", "discordGroup") .UsingJobData(defaultJobDataMap) .Build(); ITrigger countersTrigger = TriggerBuilder.Create() .WithIdentity("updateCountersTrigger", "discordGroup") //.StartAt(DateTimeOffset.UtcNow.AddSeconds(15)) //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).RepeatForever()) .WithCronSchedule("0 0/5 * 1/1 * ? *") .StartNow() .Build(); // Create job for clearing messages IJobDetail clearJob = JobBuilder.Create <ClearVcChatJob>() .WithIdentity("clearVcChatJob", "discordGroup") .UsingJobData(defaultJobDataMap) .Build(); ITrigger clearTrigger = TriggerBuilder.Create() .WithIdentity("cleatVcChatTrigger", "discordGroup") .WithCronSchedule("0 0 5 1/1 * ? *") .StartNow() //.StartAt(DateTimeOffset.UtcNow.AddSeconds(5)) //.WithSimpleSchedule(x => x.WithIntervalInMinutes(1).WithRepeatCount(0)) .Build(); IJobDetail lockdownBeginJob = JobBuilder.Create <LockdownBeginJob>() .WithIdentity("lockdownBeginJob", "discordGroup") .UsingJobData(defaultJobDataMap) .Build(); ITrigger lockdownBeginTrigger = TriggerBuilder.Create() .WithIdentity("lockdownBeginTrigger", "discordGroup") //.StartAt(DateTimeOffset.UtcNow.AddSeconds(5)) //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(0)) .WithCronSchedule("0 0 3 1/1 * ? *") .StartNow() .Build(); IJobDetail lockdownEndJob = JobBuilder.Create <LockdownEndJob>() .WithIdentity("lockdownEndJob", "discordGroup") .UsingJobData(defaultJobDataMap) .Build(); ITrigger lockdownEndTrigger = TriggerBuilder.Create() .WithIdentity("lockdownEndTrigger", "discordGroup") //.StartAt(DateTimeOffset.UtcNow.AddSeconds(15)) //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(0)) .WithCronSchedule("0 0 7 1/1 * ? *") .StartNow() .Build(); IJobDetail halfAnHourJob = JobBuilder.Create <HalfAnHourJob>() .WithIdentity("halfAnHourJob", "discordGroup") .UsingJobData(defaultJobDataMap) .Build(); ITrigger halfAnHourTrigger = TriggerBuilder.Create() .WithIdentity("halfAnHourTrigger", "discordGroup") //.StartAt(DateTimeOffset.UtcNow.AddSeconds(15)) //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(0)) .WithCronSchedule("0 0/30 * 1/1 * ? *") .StartNow() .Build(); // Schedule jobs await _scheduler.ScheduleJob(countersJob, countersTrigger); await _scheduler.ScheduleJob(clearJob, clearTrigger); await _scheduler.ScheduleJob(lockdownBeginJob, lockdownBeginTrigger); await _scheduler.ScheduleJob(lockdownEndJob, lockdownEndTrigger); await _scheduler.ScheduleJob(halfAnHourJob, halfAnHourTrigger); await _commands.AddModulesAsync(Assembly.GetExecutingAssembly(), _provider); // Load commands and modules into the command service }
public void ScheduleJob(IJobDetail jobDetail, Collection.ISet<ITrigger> triggersForJob, bool replace) { var triggersAndJobs = new Dictionary<IJobDetail, Collection.ISet<ITrigger>>(); triggersAndJobs.Add(jobDetail, triggersForJob); ScheduleJobs(triggersAndJobs, replace); }
private static async Task RunScheduler() { // 创建作业调度器 ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = await factory.GetScheduler(); // 开始运行调度器 await scheduler.Start(); // 创建一个作业 IJobDetail job = JobBuilder.Create <HelloJob>() .WithIdentity("job1", "jobGroup1") .StoreDurably() .Build(); // 设置trigger开始时间 var startAt = DateTimeOffset.Now; // 排除一天中的时间范围不执行 DailyCalendar dailyCalendar = new DailyCalendar(DateBuilder.DateOf(21, 0, 0).DateTime, DateBuilder.DateOf(22, 0, 0).DateTime); // 排除星期中的一天或多天 WeeklyCalendar weeklyCalendar = new WeeklyCalendar(); weeklyCalendar.SetDayExcluded(DayOfWeek.Friday, true); // 指定特定的日期,精确到天 HolidayCalendar holidayCalendar = new HolidayCalendar(); var holidayDateTime = new DateTime(2018, 11, 11); holidayCalendar.AddExcludedDate(holidayDateTime); // 排除月份中的某天,可选值为1-31,精确到天 MonthlyCalendar monthlyCalendar = new MonthlyCalendar(); monthlyCalendar.SetDayExcluded(31, true); // 排除每年中的某天,精确到天 AnnualCalendar annualCalendar = new AnnualCalendar(); var annualDateTime = new DateTime(2018, 11, 11); annualCalendar.SetDayExcluded(annualDateTime, true); // 使用表达式排除某些时间段不执行 CronCalendar cronCalendar = new CronCalendar("* * * 24 3 ?"); await scheduler.AddCalendar("calendar", cronCalendar, true, true); // trigger的附属信息 var triggerDataMap = new JobDataMap(); triggerDataMap.Add("name", "beck"); // 创建触发器 ITrigger trigger1 = TriggerBuilder.Create() .WithIdentity("trigger1", "triggerGroup1") .StartAt(DateBuilder.DateOf(18, 25, 40)) .WithDailyTimeIntervalSchedule(w => w .WithRepeatCount(20) .WithIntervalInSeconds(4) .WithMisfireHandlingInstructionIgnoreMisfires()) //.WithSimpleSchedule(w => w // .WithRepeatCount(20) // .WithIntervalInHours(1) // .WithMisfireHandlingInstructionNowWithExistingCount()) .UsingJobData(triggerDataMap) .WithPriority(3) .Build(); // 创建触发器 ITrigger trigger2 = TriggerBuilder.Create() .WithIdentity("trigger2", "triggerGroup1") .StartAt(startAt) .WithCronSchedule("* * * 24-25 3 ?") .ForJob(job) .UsingJobData(triggerDataMap) .ModifiedByCalendar("calendar") .WithPriority(7) .Build(); // 加入作业调度器中 await scheduler.ScheduleJob(job, trigger1); await scheduler.ScheduleJob(trigger2); await Task.Delay(TimeSpan.FromMinutes(2)); // 关闭scheduler await scheduler.Shutdown(true); }
/// <summary> /// Add the given <see cref="IJob" /> to the Scheduler - with no associated /// <see cref="ITrigger" />. The <see cref="IJob" /> will be 'dormant' until /// it is scheduled with a <see cref="ITrigger" />, or <see cref="IScheduler.TriggerJob(Quartz.JobKey)" /> /// is called for it. /// <para> /// The <see cref="IJob" /> must by definition be 'durable', if it is not, /// SchedulerException will be thrown. /// </para> /// </summary> public virtual void AddJob(IJobDetail jobDetail, bool replace) { AddJob(jobDetail, replace, false); }
private static void ScheduleJob(IJobDetail job, ITrigger trigger) { _scheduler.ScheduleJob(job, trigger).Wait(); }
/// <summary> /// Set the identity of the Job which should be fired by the produced /// Trigger, by extracting the JobKey from the given job. /// </summary> /// <remarks> /// </remarks> /// <param name="jobDetail">the Job to fire.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="ITrigger.JobKey" /> public TriggerBuilder ForJob(IJobDetail jobDetail) { JobKey k = jobDetail.Key; if (k.Name == null) { throw new ArgumentException("The given job has not yet had a name assigned to it."); } jobKey = k; return this; }
public virtual async Task Run() { ILog log = LogProvider.GetLogger(typeof(LoadExample)); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = await sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); log.Info("------- Scheduling Jobs -------------------"); Random r = new Random(); // schedule 500 jobs to run for (int count = 1; count <= NumberOfJobs; count++) { IJobDetail job = JobBuilder .Create <SimpleJob>() .WithIdentity("job" + count, "group_1") .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); // tell the job to delay some small amount... to simulate work... long timeDelay = (long)(r.NextDouble() * 2500); job.JobDataMap.Put(SimpleJob.DelayTime, timeDelay); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger_" + count, "group_1") .StartAt(DateBuilder.FutureDate(10000 + count * 100, IntervalUnit.Millisecond)) // space fire times a small bit .Build(); await sched.ScheduleJob(job, trigger); if (count % 25 == 0) { log.Info("...scheduled " + count + " jobs"); } } log.Info("------- Starting Scheduler ----------------"); // start the schedule await sched.Start(); log.Info("------- Started Scheduler -----------------"); log.Info("------- Waiting five minutes... -----------"); // wait five minutes to give our jobs a chance to run await Task.Delay(TimeSpan.FromMinutes(5)); // shut down the scheduler log.Info("------- Shutting Down ---------------------"); await sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = await sched.GetMetaData(); log.Info("Executed " + metaData.NumberOfJobsExecuted + " jobs."); }