/// <summary>
        /// Called by the <see cref="IScheduler" /> after a <see cref="IJobDetail" />
        /// has been executed, and be for the associated <see cref="ITrigger" />'s
        /// <see cref="IOperableTrigger.Triggered" /> method has been called.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        public virtual void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
        {
            ITrigger trigger = context.Trigger;

            object[] args;

            if (jobException != null)
            {
                string errMsg = jobException.Message;
                args =
                    new object[]
                {
                    context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                    trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, errMsg
                };
            }
            else
            {
                string result = Convert.ToString(context.Result, CultureInfo.InvariantCulture);
                args =
                    new object[]
                {
                    context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                    trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, result
                };
            }
        }
Exemple #2
0
        /// <summary>
        /// update trigger state
        /// if the group the trigger is in or the group the trigger's job is in are paused, then we need to check whether its job is in the blocked group, if it's then set its state to PausedBlocked, else set it to blocked.
        /// else set the trigger to the normal state (waiting), conver the nextfiretime into UTC milliseconds, so it could be stored as score in the sorted set.
        /// </summary>
        /// <param name="trigger">ITrigger</param>
        private void UpdateTriggerState(ITrigger trigger)
        {
            var triggerPausedResult =
                this.Db.SetContains(this.RedisJobStoreSchema.PausedTriggerGroupsSetKey(),
                                    this.RedisJobStoreSchema.TriggerGroupSetKey(trigger.Key.Group));
            var jobPausedResult = this.Db.SetContains(this.RedisJobStoreSchema.PausedJobGroupsSetKey(),
                                                      this.RedisJobStoreSchema.JobGroupSetKey(trigger.JobKey.Group));

            if (triggerPausedResult || jobPausedResult)
            {
                double nextFireTime = trigger.GetNextFireTimeUtc().HasValue
                                                   ? trigger.GetNextFireTimeUtc().Value.DateTime.ToUnixTimeMilliSeconds() : -1;

                var jobHashKey = this.RedisJobStoreSchema.JobHashKey(trigger.JobKey);

                if (this.Db.SetContains(this.RedisJobStoreSchema.BlockedJobsSet(), jobHashKey))
                {
                    this.SetTriggerState(RedisTriggerState.PausedBlocked,
                                         nextFireTime, this.RedisJobStoreSchema.TriggerHashkey(trigger.Key));
                }
                else
                {
                    this.SetTriggerState(RedisTriggerState.Paused,
                                         nextFireTime, this.RedisJobStoreSchema.TriggerHashkey(trigger.Key));
                }
            }
            else if (trigger.GetNextFireTimeUtc().HasValue)
            {
                this.SetTriggerState(RedisTriggerState.Waiting,
                                     trigger.GetNextFireTimeUtc().Value.DateTime.ToUnixTimeMilliSeconds(), this.RedisJobStoreSchema.TriggerHashkey(trigger.Key));
            }
        }
        public async Task TestScheduleInMiddleOfDailyInterval()
        {
            DateTimeOffset currTime = DateTimeOffset.UtcNow;

            // this test won't work out well in the early hours, where 'backing up' would give previous day,
            // or where daylight savings transitions could occur and confuse the assertions...
            if (currTime.Hour < 3)
            {
                return;
            }

            NameValueCollection properties = new NameValueCollection();

            properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType;
            ISchedulerFactory sf        = new StdSchedulerFactory(properties);
            IScheduler        scheduler = await sf.GetScheduler();

            IJobDetail job     = JobBuilder.Create <NoOpJob>().Build();
            ITrigger   trigger = TriggerBuilder.Create().WithIdentity("test")
                                 .WithDailyTimeIntervalSchedule(x => x
                                                                .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(2, 15))
                                                                .WithIntervalInMinutes(5))
                                 .StartAt(currTime)
                                 .Build();

            await scheduler.ScheduleJob(job, trigger);

            trigger = await scheduler.GetTrigger(trigger.Key);

            // Console.WriteLine("testScheduleInMiddleOfDailyInterval: currTime = " + currTime);
            // Console.WriteLine("testScheduleInMiddleOfDailyInterval: computed first fire time = " + trigger.GetNextFireTimeUtc());

            Assert.That(trigger.GetNextFireTimeUtc() > currTime, "First fire time is not after now!");

            DateTimeOffset startTime = DateBuilder.TodayAt(2, 15, 0);

            job = JobBuilder.Create <NoOpJob>().Build();

            trigger = TriggerBuilder.Create().WithIdentity("test2")
                      .WithDailyTimeIntervalSchedule(x => x
                                                     .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(2, 15))
                                                     .WithIntervalInMinutes(5))
                      .StartAt(startTime)
                      .Build();
            await scheduler.ScheduleJob(job, trigger);

            trigger = await scheduler.GetTrigger(trigger.Key);

            // Console.WriteLine("testScheduleInMiddleOfDailyInterval: startTime = " + startTime);
            // Console.WriteLine("testScheduleInMiddleOfDailyInterval: computed first fire time = " + trigger.GetNextFireTimeUtc());

            Assert.That(trigger.GetNextFireTimeUtc() == startTime);

            await scheduler.Shutdown();
        }
Exemple #4
0
        public DateTime GetNextFireTime(string group, string triggerKey)
        {
            DateTime nextFireTime = DateTime.MinValue;
            ITrigger trigger      = scheduler.GetTrigger((new TriggerKey(triggerKey, group)));

            if (trigger.GetNextFireTimeUtc().HasValue)
            {
                nextFireTime = trigger.GetNextFireTimeUtc().Value.DateTime.ToLocalTime();
            }

            return(nextFireTime);
        }
Exemple #5
0
        private List <TriggerModel> GetTriggerList(IScheduler scheduler)
        {
            var list           = new List <TriggerModel>();
            var allTriggerKeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .AnyGroup());

            foreach (var triggerKey in allTriggerKeys)
            {
                ITrigger trigger = scheduler.GetTrigger(triggerKey);

                var model = new TriggerModel()
                {
                    Name        = trigger.Key.Name,
                    Group       = trigger.Key.Group,
                    Description = trigger.Description,
                    //PreviousFireTimeUTC = trigger.GetPreviousFireTimeUtc().ToString(),
                    //NextFireTimeUTC = trigger.GetNextFireTimeUtc().ToString()
                };

                var date = trigger.GetNextFireTimeUtc()?.DateTime;
                if (date.HasValue)
                {
                    model.NextFireTimeUTC = date.Value.ToLocalTime().ToString();
                }

                list.Add(model);
            }

            return(list);
        }
Exemple #6
0
        public async Task <IActionResult> Index()
        {
            IDictionary <string, object> map = new Dictionary <string, object>()
            {
                { "Current Date Time", $"{DateTime.Now}" },
                { "Will run Time", $"{time}" },
                { "Tickets needed", $"5" },
                { "Concert Name", $"Rock" }
            };

            IJobDetail job = JobBuilder.Create <CheckAvailableTask>()
                             .WithIdentity($"Check Availablity-{time.ToString()}", GROUP_JOBS)
                             .SetJobData(new JobDataMap(map))
                             .RequestRecovery()
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity($"Check Availablity-{time.ToString()}", GROUP_JOBS)
                               .StartAt(new DateTimeOffset(time))
                               //.WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5)))
                               .WithPriority(1)
                               .Build();

            Debug.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()}");
            await _scheduler.ScheduleJob(job, trigger);

            //await UpdateTriggerAsync();
            //DeleteSchedule();

            return(View());
        }
Exemple #7
0
        protected override void OnStart(string[] args)
        {
            string DateNow, DateNext;

            base.OnStart(args);

            if (Scheduler == null)
            {
                Scheduler = StdSchedulerFactory.GetDefaultScheduler();
            }
            Scheduler.Start();

            TriggerBuilder Builder = TriggerBuilder.Create();

            Builder = Builder.WithCronSchedule(AutoOrderEmail_CronExpr, (CronSchBuilder) => {
                CronSchBuilder.InTimeZone(TimeZoneInfo.Utc);
                CronSchBuilder.WithMisfireHandlingInstructionFireAndProceed();
            });
            ITrigger   AutoEmailTrigger  = Builder.Build();
            IJobDetail AutoOrderEmailJob = JobBuilder.Create(typeof(TranslatorOfferEmailJob)).Build();

            AutoOrderEmailJob.JobDataMap["ServiceLog"] = this.ServiceLog;
            Scheduler.ScheduleJob(AutoOrderEmailJob, AutoEmailTrigger);

            DateNow  = DateTime.UtcNow.ToString("F");
            DateNext = AutoEmailTrigger.GetNextFireTimeUtc().Value.DateTime.ToString("F");
            ServiceLog.WriteEntry(string.Format(FRMT_INIT, DateNow, DateNext), EventLogEntryType.Information);

            if (this.ServiceLog.MaximumKilobytes < 51200)
            {
                this.ServiceLog.MaximumKilobytes = 51200;       // Set our custom EventLog size to 50MB
            }
        }
Exemple #8
0
        public void TestSchedulingWhenUpdatingScheduleBasedOnExistingTrigger()
        {
            DateTimeOffset    startTime        = new DateTimeOffset(2012, 12, 30, 1, 0, 0, TimeSpan.Zero);
            DateTimeOffset    previousFireTime = new DateTimeOffset(2013, 2, 15, 15, 0, 0, TimeSpan.Zero);
            SimpleTriggerImpl existing         = new SimpleTriggerImpl("triggerToReplace", "groupToReplace", startTime, null, SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromHours(1));

            existing.JobKey = new JobKey("jobName1", "jobGroup1");
            existing.SetPreviousFireTimeUtc(previousFireTime);
            existing.GetNextFireTimeUtc();

            mockScheduler.Stub(x => x.GetTrigger(existing.Key)).Return(existing);

            Stream s = ReadJobXmlFromEmbeddedResource("ScheduleRelativeToOldTrigger.xml");

            processor.ProcessStream(s, null);
            processor.ScheduleJobs(mockScheduler);

            // check that last fire time was taken from existing trigger
            mockScheduler.Stub(x => x.RescheduleJob(null, null)).IgnoreArguments();
            var      args            = mockScheduler.GetArgumentsForCallsMadeOn(x => x.RescheduleJob(null, null));
            ITrigger argumentTrigger = (ITrigger)args[0][1];

            // replacement trigger should have same start time and next fire relative to old trigger's last fire time
            Assert.That(argumentTrigger, Is.Not.Null);
            Assert.That(argumentTrigger.StartTimeUtc, Is.EqualTo(startTime));
            Assert.That(argumentTrigger.GetNextFireTimeUtc(), Is.EqualTo(previousFireTime.AddSeconds(10)));
        }
        public virtual int CompareTo(ITrigger other)
        {
            DateTimeOffset?myTime    = GetNextFireTimeUtc();
            DateTimeOffset?otherTime = other.GetNextFireTimeUtc();

            if (!myTime.HasValue && !otherTime.HasValue)
            {
                return(0);
            }

            if (!myTime.HasValue)
            {
                return(1);
            }

            if (!otherTime.HasValue)
            {
                return(-1);
            }

            if ((myTime.Value < otherTime.Value))
            {
                return(-1);
            }

            if ((myTime.Value > otherTime.Value))
            {
                return(1);
            }

            return(0);
        }
        public IList <TriggerStatusModel> GetAllTriggerStatus(string groupName)
        {
            IScheduler sched = quartzInstance.GetQuartzScheduler();

            string[] triggerNames = sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(groupName)).Result.Select(p => p.Name).ToArray();// .GetTriggerNames(groupName);
            List <TriggerStatusModel> triggerStatuses = new List <TriggerStatusModel>();

            foreach (string triggerName in triggerNames)
            {
                ITrigger       trig         = sched.GetTrigger(new TriggerKey(triggerName, groupName)).Result;
                TriggerState   st           = sched.GetTriggerState(new TriggerKey(triggerName, groupName)).Result;
                DateTimeOffset?nextFireTime = trig.GetNextFireTimeUtc();
                DateTimeOffset?lastFireTime = trig.GetPreviousFireTimeUtc();


                triggerStatuses.Add(new TriggerStatusModel()
                {
                    TriggerName  = triggerName,
                    GroupName    = groupName,
                    State        = st,
                    NextFireTime = nextFireTime.HasValue?nextFireTime.Value.ToLocalTime().ToString():"",
                    LastFireTime = lastFireTime.HasValue ? lastFireTime.Value.ToLocalTime().ToString() : "",
                    JobName      = trig.JobKey.Name
                });
            }

            return(triggerStatuses);
        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="IJobDetail" />
        /// was about to be executed (an associated <see cref="ITrigger" />
        /// has occurred), but a <see cref="ITriggerListener" /> vetoed it's
        /// execution.
        /// </summary>
        /// <seealso cref="JobToBeExecuted"/>
        public virtual Task JobExecutionVetoed(
            IJobExecutionContext context,
            CancellationToken cancellationToken = default)
        {
            if (!IsInfoEnabled)
            {
                return(Task.CompletedTask);
            }

            ITrigger trigger = context.Trigger;

            object?[] args =
            {
                context.JobDetail.Key.Name,
                context.JobDetail.Key.Group,
                SystemTime.UtcNow(),
                trigger.Key.Name,
                trigger.Key.Group,
                trigger.GetPreviousFireTimeUtc(),
                trigger.GetNextFireTimeUtc(),
                context.RefireCount
            };

            WriteInfo(string.Format(CultureInfo.InvariantCulture, JobWasVetoedMessage, args));
            return(Task.CompletedTask);
        }
        public Schedule For(ITrigger trigger)
        {
            var scheduleId  = new Guid(trigger.Key.Name);
            var jobId       = new Guid(trigger.JobKey.Name);
            var description = trigger.Description;
            var createdUtc  = new DateTime(trigger.JobDataMap.GetLong("CreatedUtc"));
            var startUtc    = trigger.StartTimeUtc.DateTime;
            var cron        = trigger.JobDataMap.ContainsKey("Cron") ? trigger.JobDataMap.GetString("Cron") : null;
            var nextUtc     = trigger.GetNextFireTimeUtc()?.DateTime;
            var previousUtc = trigger.GetPreviousFireTimeUtc()?.DateTime;
            var endUtc      = trigger.EndTimeUtc?.DateTime;

            var schedule = Schedule.Init(scheduleId, jobId, description, createdUtc, startUtc);

            if (!string.IsNullOrEmpty(cron))
            {
                schedule.WithCron(cron);
            }
            if (nextUtc.HasValue)
            {
                schedule.WithNextUtc(nextUtc.Value);
            }
            if (previousUtc.HasValue)
            {
                schedule.WithPreviousUtc(previousUtc.Value);
            }
            if (endUtc.HasValue)
            {
                schedule.WithEndUtc(endUtc.Value);
            }

            return(schedule.Build());
        }
        public async Task TestSchedulingWhenUpdatingScheduleBasedOnExistingTrigger()
        {
            DateTimeOffset    startTime        = new DateTimeOffset(2012, 12, 30, 1, 0, 0, TimeSpan.Zero);
            DateTimeOffset    previousFireTime = new DateTimeOffset(2013, 2, 15, 15, 0, 0, TimeSpan.Zero);
            SimpleTriggerImpl existing         = new SimpleTriggerImpl("triggerToReplace", "groupToReplace", startTime, null, SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromHours(1));

            existing.JobKey = new JobKey("jobName1", "jobGroup1");
            existing.SetPreviousFireTimeUtc(previousFireTime);
            existing.GetNextFireTimeUtc();

            A.CallTo(() => mockScheduler.GetTrigger(existing.Key, A <CancellationToken> ._)).Returns(existing);

            Stream s = ReadJobXmlFromEmbeddedResource("ScheduleRelativeToOldTrigger.xml");
            await processor.ProcessStream(s, null);

            await processor.ScheduleJobs(mockScheduler);

            // check that last fire time was taken from existing trigger
            A.CallTo(() => mockScheduler.RescheduleJob(null, null, A <CancellationToken> ._)).WhenArgumentsMatch(args =>
            {
                ITrigger argumentTrigger = (ITrigger)args[1];

                // replacement trigger should have same start time and next fire relative to old trigger's last fire time
                Assert.That(argumentTrigger, Is.Not.Null);
                Assert.That(argumentTrigger.StartTimeUtc, Is.EqualTo(startTime));
                Assert.That(argumentTrigger.GetNextFireTimeUtc(), Is.EqualTo(previousFireTime.AddSeconds(10)));
                return(true);
            }).MustHaveHappened();
        }
Exemple #14
0
        public void InitTrigger(ListViewItem Item, ITrigger Trigger)
        {
            Item.SubItems.Clear();
            TriggerState ts = scheduler.GetScheduler().GetTriggerState(Trigger.Key);

            Item.Text = ts.ToString();
            Item.SubItems.Add(Trigger.Key.Name);
            Item.SubItems.Add(Trigger.Key.Group);
            string express = "";

            if (Trigger is SimpleTriggerImpl)
            {
                express = string.Format("repeate {0} times;repeat-interval {1}ms", (Trigger as ISimpleTrigger).RepeatCount,
                                        (Trigger as ISimpleTrigger).RepeatInterval);
            }
            else
            {
                express = (Trigger as ICronTrigger).CronExpressionString;
            }

            Item.SubItems.Add(express);
            Item.SubItems.Add(FormatTime(Trigger.StartTimeUtc));
            Item.SubItems.Add(FormatTime2(Trigger.EndTimeUtc));
            Item.SubItems.Add(FormatTime2(Trigger.GetPreviousFireTimeUtc()));
            Item.SubItems.Add(FormatTime2(Trigger.GetNextFireTimeUtc()));
        }
        private Trigger CreateTrigger(ITrigger poTrigger)
        {
            DateTimeOffset? loNextFireTime     = poTrigger.GetNextFireTimeUtc();
            DateTimeOffset? loPreviousFireTime = poTrigger.GetPreviousFireTimeUtc();
            CronTriggerImpl loCronTrigger      = poTrigger as CronTriggerImpl;

            Trigger loTrigger = new Trigger()
            {
                Name     = poTrigger.Key.Name,
                Group    = poTrigger.Key.Group,
                TypeName = poTrigger.GetType().FullName,
                State    = this.moScheduler.GetTriggerState(poTrigger.Key).ToString()
            };

            if (loNextFireTime.HasValue)
            {
                loTrigger.NextFireTime = loNextFireTime.Value.LocalDateTime;
            }

            if (loPreviousFireTime.HasValue)
            {
                loTrigger.PreviousFireTime = loPreviousFireTime.Value.LocalDateTime;
            }

            if (loCronTrigger != null)
            {
                loTrigger.CronExpression = loCronTrigger.CronExpressionString;
            }

            return(loTrigger);
        }
Exemple #16
0
        public void startEventTimers()
        {
            Updater updater = GlobalHandlers.DatabaseHandler.getUpdater(handlers.instances.ViewerHandler.Feature.EVENTS);

            if (updater == null)
            {
                //no updater found
                GlobalHandlers.Debugger.write("There is no event updater setup.");
                return;
            }
            string       timeSelection = updater.Type;
            Update_Times updateTimes;
            string       mayBeUnused = String.Empty;
            string       cronJob     = String.Empty;

            if (timeSelection == "1")
            {
                updateTimes = Update_Times.Every_24_Hours;
                cronJob     = "0 0 8 ? * *";
            }
            IJobDetail          job     = JobBuilder.Create <EventsUpdaterJob>().WithIdentity("events", "main").Build();
            CronScheduleBuilder builder = CronScheduleBuilder.CronSchedule(cronJob);

            builder.Build();
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("events")
                               .StartNow()
                               .WithSchedule(builder).Build();

            _scheduler.ScheduleJob(job, trigger);
            Updates.NextTimeUpdate_Events = convertUTC(trigger.GetNextFireTimeUtc().ToString());
            GlobalHandlers.Debugger.write("Events trigger and job setup. Next fire is at: " + convertUTC(trigger.GetNextFireTimeUtc().ToString()));
        }
Exemple #17
0
 public TriggerInfoDto(ITrigger trigger)
 {
     TriggerKey      = trigger.Key.ToString();
     StartTimeUtc    = trigger.StartTimeUtc;
     PrevFireTimeUtc = trigger.GetPreviousFireTimeUtc();
     NextFireTimeUtc = trigger.GetNextFireTimeUtc();
     MayFireAgain    = trigger.GetMayFireAgain();
 }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> after a <see cref="IJobDetail" />
        /// has been executed, and be for the associated <see cref="ITrigger" />'s
        /// <see cref="IOperableTrigger.Triggered" /> method has been called.
        /// </summary>
        public virtual Task JobWasExecuted(
            IJobExecutionContext context,
            JobExecutionException jobException,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ITrigger trigger = context.Trigger;

            object[] args;

            if (jobException != null)
            {
                if (!IsWarnEnabled)
                {
                    return(TaskUtil.CompletedTask);
                }

                string errMsg = jobException.Message;
                args =
                    new object[]
                {
                    context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                    trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, errMsg
                };

                WriteWarning(string.Format(CultureInfo.InvariantCulture, JobFailedMessage, args), jobException);
            }
            else
            {
                if (!IsInfoEnabled)
                {
                    return(TaskUtil.CompletedTask);
                }

                string result = Convert.ToString(context.Result, CultureInfo.InvariantCulture);
                args =
                    new object[]
                {
                    context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                    trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, result
                };

                WriteInfo(string.Format(CultureInfo.InvariantCulture, JobSuccessMessage, args));
            }
            return(TaskUtil.CompletedTask);
        }
Exemple #19
0
 public void UpdateFireTimes(ITrigger trig)
 {
     NextFireTimeUtc     = trig.GetNextFireTimeUtc();
     PreviousFireTimeUtc = trig.GetPreviousFireTimeUtc();
     if (NextFireTimeUtc != null)
     {
         NextFireTimeTicks = NextFireTimeUtc.Value.UtcTicks;
     }
 }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="IJobDetail" />
        /// was about to be executed (an associated <see cref="ITrigger" />
        /// has occured), but a <see cref="ITriggerListener" /> vetoed it's
        /// execution.
        /// </summary>
        /// <param name="context"></param>
        /// <seealso cref="JobToBeExecuted(IJobExecutionContext)"/>
        public virtual void JobExecutionVetoed(IJobExecutionContext context)
        {
            ITrigger trigger = context.Trigger;

            object[] args =
                new object[]
            {
                context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount
            };
        }
        /// <summary>
        /// Called by the Quartz.IScheduler when a Quartz.Trigger has misfired.   Consideration
        /// should be given to how much time is spent in this method, as it will affect
        /// all triggers that are misfiring.  If you have lots of triggers misfiring
        /// at once, it could be an issue it this method does a lot.
        /// </summary>
        /// <param name="trigger">The Quartz.Trigger that has misfired</param>
        public Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
        {
            ILog           log      = LogManager.GetLogger(AppSettings.GetCommonLoggerName());
            DateTimeOffset?fireTime = trigger.GetNextFireTimeUtc();

            log.Info("Trigger " + trigger.Key.Name + " was misfired; scheduled time: " +
                     (fireTime != null? ((DateTimeOffset)fireTime).ToString() : "null"));
            trigger.JobDataMap[IVRSLineChecker.misfireNameTemplate] = true;

            return(Task.FromResult(true));
        }
Exemple #22
0
        private static DateTime GetNextFireTime(ITrigger trigger)
        {
            if (trigger == null)
            {
                return(DateTime.Now);
            }

            var offset = trigger.GetNextFireTimeUtc();

            return(offset.HasValue ? offset.Value.LocalDateTime : DateTime.Now);
        }
Exemple #23
0
        public static DateTime NextExecutionTime(string jobName, string groupName)
        {
            ITrigger trigger = scheduler.GetTrigger(new TriggerKey("trg_" + jobName, groupName));

            if (trigger != null)
            {
                var time = trigger.GetNextFireTimeUtc();
                return(TimeZone.CurrentTimeZone.ToLocalTime(time.Value.DateTime));
            }
            return(DateTime.MinValue);
        }
Exemple #24
0
        /// <summary>
        /// Called by the <see cref="IScheduler" /> after a <see cref="IJobDetail" />
        /// has been executed, and be for the associated <see cref="ITrigger" />'s
        /// <see cref="IOperableTrigger.Triggered" /> method has been called.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        public virtual void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
        {
            ITrigger trigger = context.Trigger;

            object[] args;

            if (jobException != null)
            {
                if (!Log.IsWarnEnabled)
                {
                    return;
                }

                string errMsg = jobException.Message;
                args =
                    new object[]
                {
                    context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                    trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, errMsg
                };

                Log.Warn(String.Format(CultureInfo.InvariantCulture, JobFailedMessage, args), jobException);
            }
            else
            {
                if (!Log.IsInfoEnabled)
                {
                    return;
                }

                string result = Convert.ToString(context.Result, CultureInfo.InvariantCulture);
                args =
                    new object[]
                {
                    context.JobDetail.Key.Name, context.JobDetail.Key.Group, SystemTime.UtcNow(), trigger.Key.Name, trigger.Key.Group,
                    trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), context.RefireCount, result
                };

                Log.Info(String.Format(CultureInfo.InvariantCulture, JobSuccessMessage, args));
            }
        }
Exemple #25
0
 private static async Task <TriggerData> GetTriggerData(IScheduler scheduler, ITrigger trigger)
 {
     return(new TriggerData(trigger.Key.Name, await GetTriggerStatus(trigger, scheduler).ConfigureAwait(false))
     {
         GroupName = trigger.Key.Group,
         StartDate = trigger.StartTimeUtc.DateTime,
         EndDate = trigger.EndTimeUtc.ToDateTime(),
         NextFireDate = trigger.GetNextFireTimeUtc().ToDateTime(),
         PreviousFireDate = trigger.GetPreviousFireTimeUtc().ToDateTime(),
         TriggerType = TriggerTypeExtractor.GetFor(trigger)
     });
 }
Exemple #26
0
 public TriggerModel(ITrigger trigger)
 {
     TriggerGroupName = trigger.Key.Group;
     TriggerName      = trigger.Key.Name;
     StartTime        = trigger.StartTimeUtc;
     EndTime          = trigger.EndTimeUtc;
     FinalFireTime    = trigger.FinalFireTimeUtc;
     Priority         = trigger.Priority;
     Description      = trigger.Description;
     JobDataMap       = trigger.JobDataMap;
     NextFireTime     = trigger.GetNextFireTimeUtc();
 }
 public TriggerModel(ITrigger trigger)
 {
     TriggerGroupName = trigger.Key.Group;
     TriggerName = trigger.Key.Name;
     StartTime = trigger.StartTimeUtc;
     EndTime = trigger.EndTimeUtc;
     FinalFireTime = trigger.FinalFireTimeUtc;
     Priority = trigger.Priority;
     Description = trigger.Description;
     JobDataMap = trigger.JobDataMap;
     NextFireTime = trigger.GetNextFireTimeUtc();
 }
 private static TriggerData GetTriggerData(IScheduler scheduler, ITrigger trigger)
 {
     return(new TriggerData(trigger.Key.Name, GetTriggerStatus(trigger, scheduler))
     {
         Group = trigger.Key.Group,
         StartDate = trigger.StartTimeUtc.DateTime,
         EndDate = trigger.EndTimeUtc.ToDateTime(),
         NextFireDate = trigger.GetNextFireTimeUtc().ToDateTime(),
         PreviousFireDate = trigger.GetPreviousFireTimeUtc().ToDateTime(),
         TriggerType = TriggerTypeExtractor.GetFor(trigger)
     });
 }
Exemple #29
0
        private static async Task InitAndStartScheduler()
        {
            // First we must get a reference to a scheduler
            var schedulerFactory = new StdSchedulerFactory();

            scheduler = await schedulerFactory.GetScheduler();

            // define the job and tie it to our job
            var        jobType = PluginLoader.GetType <IJob>(AppSettings.Get <string>("JobType"));
            IJobDetail job     = JobBuilder.Create(jobType)
                                 .WithIdentity("TradeJob", "TradingGroup")
                                 .Build();

            // Every 5 minutes, 10 seconds after the minute == "10 0/5 * * * ?".
            // Every 10 seconds (for debug purposes) == "0/10 * * * * ?"
            string   analysisCronTrigger = System.Configuration.ConfigurationManager.AppSettings["AnalysisJobCronTrigger"];
            string   tradeCronTrigger    = System.Configuration.ConfigurationManager.AppSettings["TradeJobCronTrigger"];
            ITrigger analysisTrigger     = TriggerBuilder.Create()
                                           .WithIdentity("AnalysisJobTrigger", "TradingGroup")
                                           .WithCronSchedule(analysisCronTrigger)
                                           .Build();
            ITrigger tradeTrigger = TriggerBuilder.Create()
                                    .WithIdentity("TradeJobTrigger", "TradingGroup")
                                    .WithCronSchedule(tradeCronTrigger)
                                    .Build();

            var dictionary = new Dictionary <IJobDetail, IReadOnlyCollection <ITrigger> >();

            dictionary.Add(job, new HashSet <ITrigger>()
            {
                analysisTrigger, tradeTrigger
            });

            // Tell quartz to schedule the job using our trigger
            await scheduler.ScheduleJobs(dictionary, true);

            log.Debug($"Analysis will run at: {analysisTrigger.GetNextFireTimeUtc() ?? DateTime.MinValue:r}");
            log.Debug($"Trade update will run at: {tradeTrigger.GetNextFireTimeUtc() ?? DateTime.MinValue:r}");

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await scheduler.Start();

            log.Info("Started Scheduler");

            //// wait long enough so that the scheduler as an opportunity to
            //// run the job!
            //log.Info("Waiting 65 seconds...");

            //// wait 65 seconds to show jobs
            //await Task.Delay(TimeSpan.FromSeconds(65));
        }
 private static TriggerData GetTriggerData(IScheduler scheduler, ITrigger trigger)
 {
     return(new TriggerData(
                trigger.Key.ToString(),
                trigger.Key.Group,
                trigger.Key.Name,
                GetTriggerStatus(trigger, scheduler),
                trigger.StartTimeUtc.ToUnixTicks(),
                trigger.EndTimeUtc.ToUnixTicks(),
                trigger.GetNextFireTimeUtc().ToUnixTicks(),
                trigger.GetPreviousFireTimeUtc().ToUnixTicks(),
                TriggerTypeExtractor.GetFor(trigger)));
 }
Exemple #31
0
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// has fired, it's associated <see cref="IJobDetail" />
        /// has been executed, and it's <see cref="IOperableTrigger.Triggered" /> method has been
        /// called.
        /// </summary>
        /// <param name="trigger">The <see cref="ITrigger" /> that was fired.</param>
        /// <param name="context">The <see cref="IJobExecutionContext" /> that was passed to the
        /// <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
        /// <param name="triggerInstructionCode">The result of the call on the <see cref="IOperableTrigger" />'s <see cref="IOperableTrigger.Triggered" />  method.</param>
        /// <param name="cancellationToken">The cancellation instruction.</param>
        public virtual Task TriggerComplete(
            ITrigger trigger,
            IJobExecutionContext context,
            SchedulerInstruction triggerInstructionCode,
            CancellationToken cancellationToken = default)
        {
            if (!IsInfoEnabled)
            {
                return(Task.CompletedTask);
            }

            string instrCode = "UNKNOWN";

            if (triggerInstructionCode == SchedulerInstruction.DeleteTrigger)
            {
                instrCode = "DELETE TRIGGER";
            }
            else if (triggerInstructionCode == SchedulerInstruction.NoInstruction)
            {
                instrCode = "DO NOTHING";
            }
            else if (triggerInstructionCode == SchedulerInstruction.ReExecuteJob)
            {
                instrCode = "RE-EXECUTE JOB";
            }
            else if (triggerInstructionCode == SchedulerInstruction.SetAllJobTriggersComplete)
            {
                instrCode = "SET ALL OF JOB'S TRIGGERS COMPLETE";
            }
            else if (triggerInstructionCode == SchedulerInstruction.SetTriggerComplete)
            {
                instrCode = "SET THIS TRIGGER COMPLETE";
            }

            object?[] args =
            {
                trigger.Key.Name,
                trigger.Key.Group,
                trigger.GetPreviousFireTimeUtc(),
                trigger.GetNextFireTimeUtc(),
                SystemTime.UtcNow(),
                context.JobDetail.Key.Name,
                context.JobDetail.Key.Group,
                context.RefireCount,
                triggerInstructionCode,
                instrCode
            };

            WriteInfo(string.Format(CultureInfo.InvariantCulture, TriggerCompleteMessage, args));
            return(Task.CompletedTask);
        }
Exemple #32
0
        /// <summary>
        /// Remove (delete) the <see cref="ITrigger" /> with the
        /// given name, and store the new given one - which must be associated
        /// with the same job.
        /// </summary>
        /// <param name="triggerKey">the key of the trigger</param>
        /// <param name="newTrigger">The new <see cref="ITrigger" /> to be stored.</param>
        /// <returns>
        /// 	<see langword="null" /> if a <see cref="ITrigger" /> with the given
        /// name and group was not found and removed from the store, otherwise
        /// the first fire time of the newly scheduled trigger.
        /// </returns>
        public virtual DateTimeOffset? RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger)
        {
            ValidateState();

            if (triggerKey == null)
            {
                throw new ArgumentException("triggerKey cannot be null");
            }
            if (newTrigger == null)
            {
                throw new ArgumentException("newTrigger cannot be null");
            }

            var trigger = (IOperableTrigger) newTrigger;
            ITrigger oldTrigger = GetTrigger(triggerKey);
            if (oldTrigger == null)
            {
                return null;
            }

            trigger.JobKey = oldTrigger.JobKey;
            trigger.Validate();

            ICalendar cal = null;
            if (newTrigger.CalendarName != null)
            {
                cal = resources.JobStore.RetrieveCalendar(newTrigger.CalendarName);
            }

            DateTimeOffset? ft = trigger.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);
            }

            if (resources.JobStore.ReplaceTrigger(triggerKey, trigger))
            {
                NotifySchedulerThread(newTrigger.GetNextFireTimeUtc());
                NotifySchedulerListenersUnscheduled(triggerKey);
                NotifySchedulerListenersScheduled(newTrigger);
            }
            else
            {
                return null;
            }

            return ft;
        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// has fired, it's associated <see cref="IJobDetail" />
        /// has been executed, and it's <see cref="IOperableTrigger.Triggered" /> method has been
        /// called.
        /// </summary>
        /// <param name="trigger">The <see cref="ITrigger" /> that was fired.</param>
        /// <param name="context">The <see cref="IJobExecutionContext" /> that was passed to the
        /// <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
        /// <param name="triggerInstructionCode">The result of the call on the <see cref="IOperableTrigger" />'s <see cref="IOperableTrigger.Triggered" />  method.</param>
        public virtual void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
        {
            string instrCode = "UNKNOWN";
            if (triggerInstructionCode == SchedulerInstruction.DeleteTrigger)
            {
                instrCode = "DELETE TRIGGER";
            }
            else if (triggerInstructionCode == SchedulerInstruction.NoInstruction)
            {
                instrCode = "DO NOTHING";
            }
            else if (triggerInstructionCode == SchedulerInstruction.ReExecuteJob)
            {
                instrCode = "RE-EXECUTE JOB";
            }
            else if (triggerInstructionCode ==SchedulerInstruction.SetAllJobTriggersComplete)
            {
                instrCode = "SET ALL OF JOB'S TRIGGERS COMPLETE";
            }
            else if (triggerInstructionCode == SchedulerInstruction.SetTriggerComplete)
            {
                instrCode = "SET THIS TRIGGER COMPLETE";
            }

            object[] args =
                new object[]
                    {
                        trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
                        context.JobDetail.Key.Name, context.JobDetail.Key.Group, context.RefireCount, triggerInstructionCode, instrCode
                    };
        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// has misfired.
        /// <para>
        /// Consideration should be given to how much time is spent in this method,
        /// as it will affect all triggers that are misfiring.  If you have lots
        /// of triggers misfiring at once, it could be an issue it this method
        /// does a lot.
        /// </para>
        /// </summary>
        /// <param name="trigger">The <see cref="ITrigger" /> that has misfired.</param>
        public virtual void TriggerMisfired(ITrigger trigger)
        {

            object[] args =
                new object[]
                    {
                        trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
                        trigger.JobKey.Name, trigger.JobKey.Group
                    };

        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// has misfired.
        /// <p>
        /// Consideration should be given to how much time is spent in this method,
        /// as it will affect all triggers that are misfiring.  If you have lots
        /// of triggers misfiring at once, it could be an issue it this method
        /// does a lot.
        /// </p>
        /// </summary>
        /// <param name="trigger">The <see cref="ITrigger" /> that has misfired.</param>
        public virtual void TriggerMisfired(ITrigger trigger)
        {
            if (!Log.IsInfoEnabled)
            {
                return;
            }

            object[] args =
                new object[]
                    {
                        trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
                        trigger.JobKey.Name, trigger.JobKey.Group
                    };

            Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerMisfiredMessage, args));
        }
 private static TriggerData GetTriggerData(IScheduler scheduler, ITrigger trigger)
 {
     return new TriggerData(trigger.Key.Name, GetTriggerStatus(trigger, scheduler))
     {
         GroupName = trigger.Key.Group,
         StartDate = trigger.StartTimeUtc.DateTime,
         EndDate = trigger.EndTimeUtc.ToDateTime(),
         NextFireDate = trigger.GetNextFireTimeUtc().ToDateTime(),
         PreviousFireDate = trigger.GetPreviousFireTimeUtc().ToDateTime(),
         TriggerType = TriggerTypeExtractor.GetFor(trigger)
     };
 }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// has fired, and it's associated <see cref="IJobDetail" />
        /// is about to be executed.
        /// <p>
        /// It is called before the <see cref="VetoJobExecution" /> method of this
        /// interface.
        /// </p>
        /// </summary>
        /// <param name="trigger">The <see cref="ITrigger" /> that has fired.</param>
        /// <param name="context">The <see cref="IJobExecutionContext" /> that will be passed to the <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
        public virtual void TriggerFired(ITrigger trigger, IJobExecutionContext context)
        {
            if (!Log.IsInfoEnabled)
            {
                return;
            }

            object[] args =
                new object[]
                    {
                        trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
                        context.JobDetail.Key.Name, context.JobDetail.Key.Group, context.RefireCount
                    };

            Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerFiredMessage, args));
        }
Exemple #38
0
        /// <summary>
        /// Remove (delete) the <see cref="ITrigger" /> with the
        /// given name, and store the new given one - which must be associated
        /// with the same job.
        /// </summary>
        /// <param name="triggerKey">the key of the trigger</param>
        /// <param name="newTrigger">The new <see cref="ITrigger" /> to be stored.</param>
        /// <returns>
        /// 	<see langword="null" /> if a <see cref="ITrigger" /> with the given
        /// name and group was not found and removed from the store, otherwise
        /// the first fire time of the newly scheduled trigger.
        /// </returns>
        public virtual DateTimeOffset? RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger)
        {
            ValidateState();

            IOperableTrigger trig = (IOperableTrigger) newTrigger;
            trig.Validate();

            ICalendar cal = null;
            if (newTrigger.CalendarName != null)
            {
                cal = resources.JobStore.RetrieveCalendar(newTrigger.CalendarName);
            }

            DateTimeOffset? ft = trig.ComputeFirstFireTimeUtc(cal);

            if (!ft.HasValue)
            {
                throw new SchedulerException("Based on configured schedule, the given trigger will never fire.");
            }

            if (resources.JobStore.ReplaceTrigger(triggerKey, trig))
            {
                NotifySchedulerThread(newTrigger.GetNextFireTimeUtc());
                NotifySchedulerListenersUnscheduled(triggerKey);
                NotifySchedulerListenersScheduled(newTrigger);
            }
            else
            {
                return null;
            }

            return ft;
        }
Exemple #39
0
        /// <summary>
        /// Schedule the given <see cref="ITrigger" /> with the
        /// <see cref="IJob" /> identified by the <see cref="ITrigger" />'s settings.
        /// </summary>
        public virtual async Task<DateTimeOffset> ScheduleJob(ITrigger trigger)
        {
            ValidateState();

            if (trigger == null)
            {
                throw new SchedulerException("Trigger cannot be null");
            }

            IOperableTrigger trig = (IOperableTrigger) trigger;
            trig.Validate();

            ICalendar cal = null;
            if (trigger.CalendarName != null)
            {
                cal = await resources.JobStore.RetrieveCalendar(trigger.CalendarName).ConfigureAwait(false);
                if (cal == null)
                {
                    throw new SchedulerException($"Calendar not found: {trigger.CalendarName}");
                }
            }

            DateTimeOffset? ft = trig.ComputeFirstFireTimeUtc(cal);

            if (!ft.HasValue)
            {
                var message = $"Based on configured schedule, the given trigger '{trigger.Key}' will never fire.";
                throw new SchedulerException(message);
            }

            await resources.JobStore.StoreTrigger(trig, false).ConfigureAwait(false);
            NotifySchedulerThread(trigger.GetNextFireTimeUtc());
            await NotifySchedulerListenersScheduled(trigger).ConfigureAwait(false);

            return ft.Value;
        }
Exemple #40
0
        /// <summary>
        /// Remove (delete) the <see cref="ITrigger" /> with the
        /// given name, and store the new given one - which must be associated
        /// with the same job.
        /// </summary>
        /// <param name="triggerKey">the key of the trigger</param>
        /// <param name="newTrigger">The new <see cref="ITrigger" /> to be stored.</param>
        /// <returns>
        /// 	<see langword="null" /> if a <see cref="ITrigger" /> with the given
        /// name and group was not found and removed from the store, otherwise
        /// the first fire time of the newly scheduled trigger.
        /// </returns>
        public virtual async Task<DateTimeOffset?> RescheduleJob(TriggerKey triggerKey, ITrigger newTrigger)
        {
            ValidateState();

            if (triggerKey == null)
            {
                throw new ArgumentException("triggerKey cannot be null");
            }
            if (newTrigger == null)
            {
                throw new ArgumentException("newTrigger cannot be null");
            }

            var trigger = (IOperableTrigger) newTrigger;
            ITrigger oldTrigger = await GetTrigger(triggerKey).ConfigureAwait(false);
            if (oldTrigger == null)
            {
                return null;
            }

            trigger.JobKey = oldTrigger.JobKey;
            trigger.Validate();

            ICalendar cal = null;
            if (newTrigger.CalendarName != null)
            {
                cal = await resources.JobStore.RetrieveCalendar(newTrigger.CalendarName).ConfigureAwait(false);
            }

            DateTimeOffset? ft;
            if (trigger.GetNextFireTimeUtc() != null)
            {
                // use a cloned trigger so that we don't lose possible forcefully set next fire time
                var clonedTrigger = (IOperableTrigger) trigger.Clone();
                ft = clonedTrigger.ComputeFirstFireTimeUtc(cal);
            }
            else
            {
                ft = trigger.ComputeFirstFireTimeUtc(cal);
            }

            if (!ft.HasValue)
            {
                var message = $"Based on configured schedule, the given trigger '{trigger.Key}' will never fire.";
                throw new SchedulerException(message);
            }

            if (await resources.JobStore.ReplaceTrigger(triggerKey, trigger).ConfigureAwait(false))
            {
                NotifySchedulerThread(newTrigger.GetNextFireTimeUtc());
                await NotifySchedulerListenersUnscheduled(triggerKey).ConfigureAwait(false);
                await NotifySchedulerListenersScheduled(newTrigger).ConfigureAwait(false);
            }
            else
            {
                return null;
            }

            return ft;
        }
Exemple #41
0
        /// <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;
        }
 /// <summary>
 /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
 /// has fired, and it's associated <see cref="IJobDetail" />
 /// is about to be executed.
 /// <para>
 /// It is called before the <see cref="VetoJobExecution" /> method of this
 /// interface.
 /// </para>
 /// </summary>
 /// <param name="trigger">The <see cref="ITrigger" /> that has fired.</param>
 /// <param name="context">The <see cref="IJobExecutionContext" /> that will be passed to the <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
 public virtual void TriggerFired(ITrigger trigger, IJobExecutionContext context)
 {
     object[] args =
         new object[]
             {
                 trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
                 context.JobDetail.Key.Name, context.JobDetail.Key.Group, context.RefireCount
             };
 }
Exemple #43
0
        /// <summary>
        /// Schedule the given <see cref="ITrigger" /> with the
        /// <see cref="IJob" /> identified by the <see cref="ITrigger" />'s settings.
        /// </summary>
        public virtual DateTimeOffset ScheduleJob(ITrigger trigger)
        {
            ValidateState();

            if (trigger == null)
            {
                throw new SchedulerException("Trigger cannot be null");
            }

            IOperableTrigger trig = (IOperableTrigger) trigger;
            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.StoreTrigger(trig, false);
            NotifySchedulerThread(trigger.GetNextFireTimeUtc());
            NotifySchedulerListenersScheduled(trigger);

            return ft.Value;
        }
        /// <summary>
        /// update trigger state
        /// if the group the trigger is in or the group the trigger's job is in are paused, then we need to check whether its job is in the blocked group, if it's then set its state to PausedBlocked, else set it to blocked.  
        /// else set the trigger to the normal state (waiting), conver the nextfiretime into UTC milliseconds, so it could be stored as score in the sorted set. 
        /// </summary>
        /// <param name="trigger">ITrigger</param>
        private void UpdateTriggerState(ITrigger trigger)
        {
            var triggerPausedResult =
                this.Db.SetContains(this.RedisJobStoreSchema.PausedTriggerGroupsSetKey(),
                                     this.RedisJobStoreSchema.TriggerGroupSetKey(trigger.Key.Group));
            var jobPausedResult = this.Db.SetContains(this.RedisJobStoreSchema.PausedJobGroupsSetKey(),
                                                         this.RedisJobStoreSchema.JobGroupSetKey(trigger.JobKey.Group));

            if (triggerPausedResult || jobPausedResult)
            {
                double nextFireTime = trigger.GetNextFireTimeUtc().HasValue
                                                   ? trigger.GetNextFireTimeUtc().Value.DateTime.ToUnixTimeMilliSeconds() : -1;

                var jobHashKey = this.RedisJobStoreSchema.JobHashKey(trigger.JobKey);

                if (this.Db.SetContains(this.RedisJobStoreSchema.BlockedJobsSet(), jobHashKey))
                {
                    this.SetTriggerState(RedisTriggerState.PausedBlocked,
                        nextFireTime, this.RedisJobStoreSchema.TriggerHashkey(trigger.Key));
                }
                else
                {
                    this.SetTriggerState(RedisTriggerState.Paused,
                        nextFireTime, this.RedisJobStoreSchema.TriggerHashkey(trigger.Key));
                }
            }
            else if (trigger.GetNextFireTimeUtc().HasValue)
            {
                this.SetTriggerState(RedisTriggerState.Waiting,
                       trigger.GetNextFireTimeUtc().Value.DateTime.ToUnixTimeMilliSeconds(), this.RedisJobStoreSchema.TriggerHashkey(trigger.Key));
            }
        }