public async Task Should_Create_Activity_And_Enrich_When_Enrich()
        {
            // Arrange
            Barrier         barrier           = new Barrier(2);
            List <DateTime> jobExecTimestamps = new List <DateTime>();

            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            var jobDataMapPropertyFetcher = new PropertyFetcher <object>("JobDataMap");

            using var tel = Sdk.CreateTracerProviderBuilder()
                            .SetSampler(new AlwaysOnSampler())
                            .AddQuartzInstrumentation(q =>
                                                      q.Enrich = (a, s, payload) =>
            {
                if (payload is IJobDetail jobDetail)
                {
                    var dataMap = jobDetail.JobDataMap;
                    if (dataMap.ContainsKey("TestId"))
                    {
                        a.SetTag("test.id", dataMap["TestId"]);
                    }
                }
            })
                            .AddProcessor(activityProcessor.Object)
                            .Build();

            var schedulerConfig = SchedulerBuilder.Create("AUTO", "Scheduler");

            schedulerConfig.UseDefaultThreadPool(x => x.MaxConcurrency = 10);
            var scheduler = await schedulerConfig.BuildScheduler();

            scheduler.Context.Put("BARRIER", barrier);
            scheduler.Context.Put("DATESTAMPS", jobExecTimestamps);
            await scheduler.Start();

            var        testId     = Guid.NewGuid().ToString();
            JobDataMap jobDataMap = new JobDataMap {
                { "TestId", testId }
            };

            var name = Guid.NewGuid().ToString();
            var job  = JobBuilder.Create <TestJob>()
                       .WithIdentity(name, SchedulerConstants.DefaultGroup)
                       .UsingJobData(jobDataMap)
                       .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(name, SchedulerConstants.DefaultGroup)
                          .StartNow()
                          .Build();

            // Act
            await scheduler.ScheduleJob(job, trigger);

            barrier.SignalAndWait(TestTimeout);

            await scheduler.Shutdown(true);

            // Assert
            Assert.Equal(3, activityProcessor.Invocations.Count);
            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Equal("Quartz.Job.Execute", activity.OperationName);
            Assert.Equal(ActivityKind.Internal, activity.Kind);
            Assert.Equal("Scheduler", activity.Tags.SingleOrDefault(t => t.Key.Equals("scheduler.name")).Value);
            Assert.Equal(SchedulerConstants.DefaultGroup, activity.Tags.SingleOrDefault(t => t.Key.Equals("job.group")).Value);
            Assert.Equal(SchedulerConstants.DefaultGroup, activity.Tags.SingleOrDefault(t => t.Key.Equals("trigger.group")).Value);
            Assert.Equal(testId, activity.Tags.SingleOrDefault(t => t.Key.Equals("test.id")).Value);
        }
        /// <summary>
        /// Handles with a given text matches the Expression3 field.
        /// </summary>
        /// <param name="nameValueCollection">A collection of values from the named capture groups.</param>
        /// <param name="results">The results.</param>
        private void Expression3Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results)
        {
            var timesToFire = nameValueCollection.GetValues("TIME");

            var dateSpec    = nameValueCollection["DATESPEC"];
            var monthString = nameValueCollection["MONTH"];
            var dayString   = nameValueCollection["DAY"];
            var yearString  = nameValueCollection["YEAR"];

            //init cron values
            List <string> cronExpressions = new List <string>();

            if (timesToFire == null) // if times are not specified assume midnight
            {
                timesToFire = new string[] { "00:00" }
            }
            ;

            foreach (var time in timesToFire)
            {
                DateTime date = DateTime.Today; //default date to today

                if (time != null)
                {
                    date = GrammarHelper.GetTimeFromTimeString(time).Value;
                }

                string cron_sec       = date.Second.ToString();
                string cron_min       = date.Minute.ToString();
                string cron_hour      = date.Hour.ToString();
                string cron_day       = "*";
                string cron_month     = "*";
                string cron_dayofWeek = "?";
                string cron_year      = null;

                cron_month = GetMonthCronValue(GrammarHelper.GetMonthValue(monthString));

                if (dayString != null)
                {
                    cron_day = GetDayCronValue(GrammarHelper.GetDayValue(dayString));
                }
                else
                {
                    cron_day = GetDayCronValue(1);
                }

                if (yearString != null)
                {
                    cron_year = GetYearCronValue(GrammarHelper.GetYearValue(yearString));
                }


                //build cron string
                string cronString = null;

                if (cron_year != null)
                {
                    cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek, cron_year }));
                }
                else
                {
                    cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek }));
                }

                //add cron string
                cronExpressions.Add(cronString);
            }

            foreach (var cron in cronExpressions)
            {
                var triggerBuilder = TriggerBuilder.Create();

                IScheduleBuilder schedule = CreateScheduleWithCron(cron, timeZone);
                triggerBuilder.WithSchedule(schedule);

                results.Add(triggerBuilder);
            }
        }
예제 #3
0
        /// <summary>
        /// Schedules a job of the provided type to run immediatly.
        /// </summary>
        public static DateTimeOffset StartJob(this IScheduler scheduler, Type jobType)
        {
            ITrigger trigger = TriggerBuilder.Create().StartNow().Build();

            return(scheduler.ScheduleJob(jobType, trigger));
        }
예제 #4
0
        public async void Start(int hourStart, int minStart, int hourEnd, int minEnd, int intervalInHour, object obj, List <jours> jours, string type)

        {
            DateTime            now       = DateTime.Now;
            DateTime            firstRun  = new DateTime(now.Year, now.Month, now.Day, hourStart, minStart, 0, 0);
            DateTime            lastRun   = new DateTime(now.Year, now.Month, now.Day, hourEnd, minEnd, 0, 0);
            StdSchedulerFactory factory   = new StdSchedulerFactory();
            IScheduler          scheduler = await factory.GetScheduler();

            await scheduler.Start();

            //Console.WriteLine(obj.GetType().Name);
            switch (obj.GetType().Name)
            {
            case "JobArticles":
                job = JobBuilder.Create <JobArticles>().Build();
                break;

            case "JobAttributsCaracteristiques":
                job = JobBuilder.Create <JobAttributsCaracteristiques>().Build();
                break;

            case "JobClients":
                job = JobBuilder.Create <JobClients>().Build();
                break;

            case "JobCommand":
                job = JobBuilder.Create <JobCommand>().Build();
                break;

            case "JobCopiePhotos":
                job = JobBuilder.Create <JobCopiePhotos>().Build();
                break;

            case "JobGamme":
                job = JobBuilder.Create <JobGamme>().Build();
                break;

            case "JobNettoyagePhotos":
                job = JobBuilder.Create <JobNettoyagePhotos>().Build();
                break;

            case "JobPhotos":
                job = JobBuilder.Create <JobPhotos>().Build();
                break;

            case "JobPrix":
                job = JobBuilder.Create <JobPrix>().Build();
                break;

            case "JobStock":
                job = JobBuilder.Create <JobStock>().Build();
                break;

            case "JobArticlesKnco":
                job = JobBuilder.Create <JobArticlesKnco>().Build();
                break;

            default:
                Console.WriteLine(obj.GetType().Name);
                break;
            }


            if (jours != null)
            {
                foreach (jours jour in jours)
                {
                    if (type == "Minutes")
                    {
                        ITrigger trigger = TriggerBuilder.Create()
                                           .WithIdentity("IDGJob", "IDG")
                                           .StartAt(firstRun).EndAt(lastRun)
                                           .WithCronSchedule("0 0/" + intervalInHour + " * ? * " + jour.variable)
                                           .Build();
                        scheduler.ScheduleJob(job, trigger);
                    }
                    else
                    {
                        ITrigger trigger = TriggerBuilder.Create()
                                           .WithIdentity("IDGJob", "IDG")
                                           .StartAt(firstRun).EndAt(lastRun)
                                           .WithCronSchedule("0 0 " + intervalInHour + " ? * " + jour.variable)
                                           .Build();
                        scheduler.ScheduleJob(job, trigger);
                    }
                }
            }
            else
            {
                if (type == "Minutes")
                {
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity("IDGJob", "IDG")
                                       .StartAt(firstRun).EndAt(lastRun)
                                       .WithCronSchedule("0 0/" + intervalInHour + " * ? * *")
                                       .Build();
                    scheduler.ScheduleJob(job, trigger);
                }
                else
                {
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity("IDGJob", "IDG")
                                       .StartAt(firstRun).EndAt(lastRun)
                                       .WithCronSchedule("0 0 " + intervalInHour + " ? * *")
                                       .Build();
                    scheduler.ScheduleJob(job, trigger);
                }
            }

            /*ITrigger trigger = TriggerBuilder.Create()
             * .WithIdentity("IDGJob", "IDG")
             * .StartAt(firstRun).EndAt(lastRun).WithCronSchedule("")
             * .WithPriority(1)
             * .Build();*/
            //await scheduler.ScheduleJob(job, trigger);
        }
        /// <summary>
        /// Handles with a given text matches the Expression1 field.
        /// </summary>
        /// <param name="nameValueCollection">A collection of values from the named capture groups.</param>
        /// <param name="results">The results.</param>
        private void Expression1Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results)
        {
            var amountString       = nameValueCollection["AMOUNT"];
            var intervalUnitString = nameValueCollection["INTERVALUNIT"];
            var startDateString    = nameValueCollection["DATESPEC"];

            var time     = nameValueCollection["TIME"];
            var fromTime = nameValueCollection["FROMTIME"];
            var toTime   = nameValueCollection["TOTIME"];

            var dayOfWeekSpecs = nameValueCollection.GetValues("DAYOFWEEK");
            var monthSpecs     = nameValueCollection.GetValues("MONTH");

            DateTime?triggerStartTime = null;

            ICalendar calendar = null;

            //DAY OF WEEK SPECS
            if (dayOfWeekSpecs != null)
            {
                calendar = BuildCalendarOnDayOfWeek(calendar, dayOfWeekSpecs, timeZone);
            }

            //MONTH SPECS
            if (monthSpecs != null)
            {
                calendar = BuildCalendarOnMonths(calendar, monthSpecs, timeZone);
            }


            //TIME (single or range)

            //check for ranged time
            if (fromTime != null && toTime != null)
            {
                calendar = BuildCalendarOnTimeRange(calendar, fromTime, toTime, timeZone);

                //set the start date as the from time
                DateTime?fromTimeStartDate = GrammarHelper.GetTimeFromTimeString(fromTime);
                triggerStartTime = fromTimeStartDate;
            }
            //is regular time, process as single time provided
            else if (time != null)
            {
                DateTime?timeStartDate = GrammarHelper.GetTimeFromTimeString(time);
                triggerStartTime = timeStartDate;
            }

            //BUILD TRIGGER
            TriggerBuilder triggerBuilder = TriggerBuilder.Create();

            //set schedule
            triggerBuilder.WithSchedule(CreateScheduleWithAmountAndIntervalUnit(amountString, intervalUnitString, timeZone));


            //start on from time
            if (triggerStartTime != null)
            {
                triggerBuilder.StartAt(new DateTimeOffset(triggerStartTime.Value, timeZone.GetUtcOffset(triggerStartTime.Value)));
            }

            results.Add(triggerBuilder, calendar);
        }
        public async Task TestBasicStorageFunctions()
        {
            var sched = await CreateScheduler("TestBasicStorageFunctions", 2);

            await sched.Start(CancellationToken.None);

            await sched.Standby(CancellationToken.None);

            // test basic storage functions of scheduler...

            var job = JobBuilder.Create()
                      .OfType <TestJob>()
                      .WithIdentity("j1")
                      .StoreDurably()
                      .Build();

            Assert.IsFalse(await sched.CheckExists(new JobKey("j1")), "Unexpected existence of job named 'j1'.");

            await sched.AddJob(job, false);

            Assert.IsTrue(await sched.CheckExists(new JobKey("j1")),
                          "Expected existence of job named 'j1' but checkExists return false.");

            job = await sched.GetJobDetail(new JobKey("j1"));

            Assert.IsNotNull(job, "Stored job not found!");

            await sched.DeleteJob(new JobKey("j1"));

            var trigger = TriggerBuilder.Create()
                          .WithIdentity("t1")
                          .ForJob(job)
                          .StartNow()
                          .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                          .Build();

            Assert.IsFalse(await sched.CheckExists(new TriggerKey("t1")),
                           "Unexpected existence of trigger named '11'.");

            await sched.ScheduleJob(job, trigger);

            Assert.IsTrue(await sched.CheckExists(new TriggerKey("t1")),
                          "Expected existence of trigger named 't1' but checkExists return false.");

            job = await sched.GetJobDetail(new JobKey("j1"));

            Assert.IsNotNull(job, "Stored job not found!");

            trigger = await sched.GetTrigger(new TriggerKey("t1"));

            Assert.IsNotNull(trigger, "Stored trigger not found!");

            job = JobBuilder.Create()
                  .OfType <TestJob>()
                  .WithIdentity("j2", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t2", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                      .Build();

            await sched.ScheduleJob(job, trigger);

            job = JobBuilder.Create()
                  .OfType <TestJob>()
                  .WithIdentity("j3", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t3", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                      .Build();

            await sched.ScheduleJob(job, trigger);


            IList <string> jobGroups     = (await sched.GetJobGroupNames()).ToList();
            IList <string> triggerGroups = (await sched.GetTriggerGroupNames()).ToList();

            Assert.AreEqual(3, jobGroups.Count, "Job group list size expected to be = 2 + 1 for DEFAULT");
            Assert.AreEqual(2, triggerGroups.Count, "Trigger group list size expected to be = 2");

            ISet <JobKey> jobKeys = (await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(JobKey.DefaultGroup)))
                                    .ToHashSet();
            ISet <TriggerKey> triggerKeys =
                (await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(TriggerKey.DefaultGroup))).ToHashSet();

            Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 ");
            Assert.AreEqual(1, triggerKeys.Count, "Number of triggers expected in default group was 1 ");

            jobKeys     = (await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("g1"))).ToHashSet();
            triggerKeys = (await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("g1"))).ToHashSet();

            Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 2 ");
            Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 2 ");


            var s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            await sched.PauseTrigger(new TriggerKey("t2", "g1"));

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED ");

            await sched.ResumeTrigger(new TriggerKey("t2", "g1"));

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            ISet <string> pausedGroups = (await sched.GetPausedTriggerGroups()).ToHashSet();

            Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 ");

            await sched.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            // test that adding a trigger to a paused group causes the new trigger to be paused also...
            job = JobBuilder.Create()
                  .OfType <TestJob>()
                  .WithIdentity("j4", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t4", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                      .Build();

            await sched.ScheduleJob(job, trigger);

            pausedGroups = (await sched.GetPausedTriggerGroups()).ToHashSet();
            Assert.AreEqual(1, pausedGroups.Count, "Size of paused trigger groups list expected to be 1 ");

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED ");

            s = await sched.GetTriggerState(new TriggerKey("t4", "g1"));

            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t4 expected to be PAUSED");

            await sched.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            s = await sched.GetTriggerState(new TriggerKey("t4", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            pausedGroups = (await sched.GetPausedTriggerGroups()).ToHashSet();
            Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 ");


            Assert.IsFalse(await sched.UnscheduleJob(new TriggerKey("foasldfksajdflk")),
                           "Scheduler should have returned 'false' from attempt to unschedule non-existing trigger. ");

            Assert.IsTrue(await sched.UnscheduleJob(new TriggerKey("t3", "g1")),
                          "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ");

            jobKeys     = (await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("g1"))).ToHashSet();
            triggerKeys = (await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("g1"))).ToHashSet();

            Assert.AreEqual(2, jobKeys.Count,
                            "Number of jobs expected in 'g1' group was 2 "); // job should have been deleted also, because it is non-durable
            Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 2 ");

            Assert.IsTrue(await sched.UnscheduleJob(new TriggerKey("t1")),
                          "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ");

            jobKeys     = (await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(JobKey.DefaultGroup))).ToHashSet();
            triggerKeys = (await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(TriggerKey.DefaultGroup)))
                          .ToHashSet();

            Assert.AreEqual(1, jobKeys.Count,
                            "Number of jobs expected in default group was 1 "); // job should have been left in place, because it is non-durable
            Assert.AreEqual(0, triggerKeys.Count, "Number of triggers expected in default group was 0 ");

            await sched.Shutdown();
        }
예제 #7
0
        public void ScheduleWorkflow(Workflow wf)
        {
            if (wf.IsEnabled)
            {
                if (wf.LaunchType == LaunchType.Startup)
                {
                    wf.Start();
                }
                else if (wf.LaunchType == LaunchType.Periodic)
                {
                    IDictionary <string, object> map = new Dictionary <string, object>();
                    map.Add("workflow", wf);

                    string     jobIdentity = "Workflow Job " + wf.Id;
                    IJobDetail jobDetail   = JobBuilder.Create <WorkflowJob>()
                                             .WithIdentity(jobIdentity)
                                             .SetJobData(new JobDataMap(map))
                                             .Build();

                    ITrigger trigger = TriggerBuilder.Create()
                                       .ForJob(jobDetail)
                                       .WithSimpleSchedule(x => x.WithInterval(wf.Period).RepeatForever())
                                       .WithIdentity("Workflow Trigger " + wf.Id)
                                       .StartNow()
                                       .Build();

                    var jobKey = new JobKey(jobIdentity);
                    if (QuartzScheduler.CheckExists(jobKey).Result)
                    {
                        QuartzScheduler.DeleteJob(jobKey);
                    }

                    QuartzScheduler.ScheduleJob(jobDetail, trigger).Wait();
                }
                else if (wf.LaunchType == LaunchType.Cron)
                {
                    IDictionary <string, object> map = new Dictionary <string, object>();
                    map.Add("workflow", wf);

                    string     jobIdentity = "Workflow Job " + wf.Id;
                    IJobDetail jobDetail   = JobBuilder.Create <WorkflowJob>()
                                             .WithIdentity(jobIdentity)
                                             .SetJobData(new JobDataMap(map))
                                             .Build();

                    ITrigger trigger = TriggerBuilder.Create()
                                       .ForJob(jobDetail)
                                       .WithCronSchedule(wf.CronExpression)
                                       .WithIdentity("Workflow Trigger " + wf.Id)
                                       .StartNow()
                                       .Build();

                    var jobKey = new JobKey(jobIdentity);
                    if (QuartzScheduler.CheckExists(jobKey).Result)
                    {
                        QuartzScheduler.DeleteJob(jobKey);
                    }

                    QuartzScheduler.ScheduleJob(jobDetail, trigger).Wait();
                }
            }
        }
예제 #8
0
        public static void Start()
        {
            Debug.WriteLine("Start advertise call");

            var scheduler1 = StdSchedulerFactory.GetDefaultScheduler();
            var job1       = JobBuilder.Create <Ad1>()
                             .UsingJobData("BOX_NAME", "L-1")
                             .Build();
            var trigger1 = TriggerBuilder.Create()
                           .WithIdentity("trigger1", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler1.ScheduleJob(job1, trigger1);


            var scheduler2 = StdSchedulerFactory.GetDefaultScheduler();
            var job2       = JobBuilder.Create <Ad2>()
                             .UsingJobData("BOX_NAME", "L-2")
                             .Build();
            var trigger2 = TriggerBuilder.Create()
                           .WithIdentity("trigger2", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler2.ScheduleJob(job2, trigger2);

            var scheduler3 = StdSchedulerFactory.GetDefaultScheduler();
            var job3       = JobBuilder.Create <Ad3>()
                             .UsingJobData("BOX_NAME", "L-3")
                             .Build();
            var trigger3 = TriggerBuilder.Create()
                           .WithIdentity("trigger3", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler3.ScheduleJob(job3, trigger3);

            var scheduler4 = StdSchedulerFactory.GetDefaultScheduler();
            var job4       = JobBuilder.Create <Ad4>()
                             .UsingJobData("BOX_NAME", "M-1")
                             .Build();
            var trigger4 = TriggerBuilder.Create()
                           .WithIdentity("trigger4", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler4.ScheduleJob(job4, trigger4);

            var scheduler5 = StdSchedulerFactory.GetDefaultScheduler();
            var job5       = JobBuilder.Create <Ad5>()
                             .UsingJobData("BOX_NAME", "M-2")
                             .Build();
            var trigger5 = TriggerBuilder.Create()
                           .WithIdentity("trigger5", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler5.ScheduleJob(job5, trigger5);

            var scheduler6 = StdSchedulerFactory.GetDefaultScheduler();
            var job6       = JobBuilder.Create <Ad6>()
                             .UsingJobData("BOX_NAME", "M-3")
                             .Build();
            var trigger6 = TriggerBuilder.Create()
                           .WithIdentity("trigger6", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler6.ScheduleJob(job6, trigger6);

            var scheduler7 = StdSchedulerFactory.GetDefaultScheduler();
            var job7       = JobBuilder.Create <Ad7>()
                             .UsingJobData("BOX_NAME", "R-1")
                             .Build();
            var trigger7 = TriggerBuilder.Create()
                           .WithIdentity("trigger7", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler7.ScheduleJob(job7, trigger7);

            var scheduler8 = StdSchedulerFactory.GetDefaultScheduler();
            var job8       = JobBuilder.Create <Ad8>()
                             .UsingJobData("BOX_NAME", "R-2")
                             .Build();
            var trigger8 = TriggerBuilder.Create()
                           .WithIdentity("trigger8", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler8.ScheduleJob(job8, trigger8);

            var scheduler9 = StdSchedulerFactory.GetDefaultScheduler();
            var job9       = JobBuilder.Create <Ad9>()
                             .UsingJobData("BOX_NAME", "R-3")
                             .Build();
            var trigger9 = TriggerBuilder.Create()
                           .WithIdentity("trigger9", "group1")
                           .StartNow()
                           .WithSimpleSchedule(s => s
                                               .WithIntervalInSeconds(1)
                                               .RepeatForever()
                                               )
                           .Build();

            scheduler9.ScheduleJob(job9, trigger9);
        }
예제 #9
0
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <typeparam name="T">任务类型,继承Ijop</typeparam>
        /// <param name="jopName">任务名</param>
        /// <param name="Interval">运行间隔时间/秒**最小为1秒</param>
        /// <param name="period">等待启动时间/秒**-1为马上启动</param>
        /// <param name="repeatTime">重复次数**-1为永远运行</param>
        /// <param name="endAt">在指定时间后结束/秒**0为不指定结束时间,默认值0</param>
        public static void PushJop <T>(string jopName, int Interval, int period = -1, int repeatTime = -1, int endAt = 0)  where T : IJob
        {
            try
            {
                if (Interval <= 0)
                {
                    Interval = 1;
                }
                if (period < -1)
                {
                    period = -1;
                }
                if (repeatTime < -1)
                {
                    repeatTime = -1;
                }
                if (endAt < 0)
                {
                    endAt = -1;
                }

                IJobDetail job = JobBuilder.Create <T>().WithIdentity(jopName, defaultGroupName).UsingJobData("Name", "IJobDetail").Build();


                var triggerBuilder = TriggerBuilder.Create().WithIdentity($"{jopName}.trigger{triggerId}", defaultGroupName);


                if (period == -1)
                {
                    triggerBuilder = triggerBuilder.StartNow();
                }
                else
                {
                    DateTimeOffset dateTimeOffset = DateTimeOffset.Now.AddSeconds(period);
                    triggerBuilder = triggerBuilder.StartAt(dateTimeOffset);
                }
                if (endAt > 0)
                {
                    triggerBuilder = triggerBuilder.EndAt(new DateTimeOffset(DateTime.Now.AddSeconds(endAt)));
                }

                if (repeatTime == -1)
                {
                    triggerBuilder = triggerBuilder.WithSimpleSchedule(x => x.WithIntervalInSeconds(Interval).RepeatForever());
                }
                else
                {
                    triggerBuilder = triggerBuilder.WithSimpleSchedule(x => x.WithRepeatCount(Interval).WithRepeatCount(repeatTime));
                }


                ITrigger trigger = triggerBuilder.UsingJobData("Name", "ITrigger")
                                   .WithPriority(triggerId)//设置触发器优先级,当有多个触发器在相同时间出发时,优先级最高[数字最大]的优先
                                   .Build();

                dicJop.Add(job, new HashSet <ITrigger>()
                {
                    trigger
                });
                triggerId++;
            }
            catch (SchedulerException se)
            {
                System.Console.WriteLine(se);
            }
        }
예제 #10
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(LoadExample));

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = sf.GetScheduler();

            log.Info("------- Initialization Complete -----------");

            log.Info("------- (Not Scheduling any Jobs - relying on XML definitions --");

            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)), DateBuilder.IntervalUnit.Millisecond)) // space fire times a small bit
                                   .Build();

                sched.ScheduleJob(job, trigger);
                if (count % 25 == 0)
                {
                    log.Info("...scheduled " + count + " jobs");
                }
            }


            log.Info("------- Starting Scheduler ----------------");

            // start the schedule
            sched.Start();

            log.Info("------- Started Scheduler -----------------");

            log.Info("------- Waiting five minutes... -----------");

            // wait five minutes to give our jobs a chance to run
            try
            {
                Thread.Sleep(TimeSpan.FromMinutes(5));
            }
            catch (ThreadInterruptedException)
            {
            }

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info("Executed " + metaData.NumberOfJobsExecuted + " jobs.");
        }
예제 #11
0
        public static void Start()
        {
            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_Pruebas = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_Pruebas.Start();
            IJobDetail job_Pruebas = JobBuilder.Create <Pruebas>().Build();

            ITrigger trigger_Pruebas = TriggerBuilder.Create()
                                       .WithIdentity("Pruebas", "group1")
                                       .StartNow()
                                       .WithSimpleSchedule(x => x
                                                           .WithIntervalInMinutes(1)
                                                           .RepeatForever())
                                       .Build();

            scheduler_Pruebas.ScheduleJob(job_Pruebas, trigger_Pruebas);

            ///////////////////  SCHEDULER 1 MINUTO  //////////////////////////////////
            IScheduler scheduler_SincronizaCada1min = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada1min.Start();
            IJobDetail job_SincronizaCada1min = JobBuilder.Create <SincronizaCada1min>().Build();

            ITrigger trigger_SincronizaCada1min = TriggerBuilder.Create()
                                                  .WithIdentity("trigger_SincronizaCada1min", "group1")
                                                  .StartNow()
                                                  .WithSimpleSchedule(x => x
                                                                      .WithIntervalInMinutes(1)
                                                                      .RepeatForever())
                                                  .Build();

            scheduler_SincronizaCada1min.ScheduleJob(job_SincronizaCada1min, trigger_SincronizaCada1min);

            ///////////////////  SCHEDULER 2 MINUTOS  //////////////////////////////////
            IScheduler scheduler_SincronizaCada2min = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada2min.Start();
            IJobDetail job_SincronizaCada2min = JobBuilder.Create <SincronizaCada2min>().Build();

            ITrigger trigger_SincronizaCada2min = TriggerBuilder.Create()
                                                  .WithIdentity("trigger_SincronizaCada2min", "group1")
                                                  .StartNow()
                                                  .WithSimpleSchedule(x => x
                                                                      .WithIntervalInMinutes(2)
                                                                      .RepeatForever())
                                                  .Build();

            scheduler_SincronizaCada2min.ScheduleJob(job_SincronizaCada2min, trigger_SincronizaCada2min);

            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_SincronizaCada3min = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada3min.Start();
            IJobDetail job_SincronizaCada3min = JobBuilder.Create <SincronizaCada3min>().Build();

            ITrigger trigger_SincronizaCada3min = TriggerBuilder.Create()
                                                  .WithIdentity("trigger_SincronizaCada3min", "group1")
                                                  .StartNow()
                                                  .WithSimpleSchedule(x => x
                                                                      .WithIntervalInMinutes(3)
                                                                      .RepeatForever())
                                                  .Build();

            scheduler_SincronizaCada3min.ScheduleJob(job_SincronizaCada3min, trigger_SincronizaCada3min);

            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_SincronizaCada4min = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada4min.Start();
            IJobDetail job_SincronizaCada4min = JobBuilder.Create <SincronizaCada4min>().Build();

            ITrigger trigger_SincronizaCada4min = TriggerBuilder.Create()
                                                  .WithIdentity("trigger_SincronizaCada4min", "group1")
                                                  .StartNow()
                                                  .WithSimpleSchedule(x => x
                                                                      .WithIntervalInMinutes(4)
                                                                      .RepeatForever())
                                                  .Build();

            scheduler_SincronizaCada4min.ScheduleJob(job_SincronizaCada4min, trigger_SincronizaCada4min);

            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_SincronizaCada5min = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada5min.Start();
            IJobDetail job_SincronizaCada5min = JobBuilder.Create <SincronizaCada5min>().Build();

            ITrigger trigger_SincronizaCada5min = TriggerBuilder.Create()
                                                  .WithIdentity("trigger_SincronizaCada5min", "group1")
                                                  .StartNow()
                                                  .WithSimpleSchedule(x => x
                                                                      .WithIntervalInMinutes(5)
                                                                      .RepeatForever())
                                                  .Build();

            scheduler_SincronizaCada5min.ScheduleJob(job_SincronizaCada5min, trigger_SincronizaCada5min);

            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_SincronizaCada10min = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada10min.Start();
            IJobDetail job_SincronizaCada10min = JobBuilder.Create <SincronizaCada10min>().Build();

            ITrigger trigger_SincronizaCada10min = TriggerBuilder.Create()
                                                   .WithIdentity("trigger_SincronizaCada10min", "group1")
                                                   .StartNow()
                                                   .WithSimpleSchedule(x => x
                                                                       .WithIntervalInMinutes(10)
                                                                       .RepeatForever())
                                                   .Build();

            scheduler_SincronizaCada10min.ScheduleJob(job_SincronizaCada10min, trigger_SincronizaCada10min);

            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_SincronizaCada30seg = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_SincronizaCada30seg.Start();
            IJobDetail job_SincronizaCada30seg = JobBuilder.Create <SincronizaCada30seg>().Build();

            ITrigger trigger_SincronizaCada30seg = TriggerBuilder.Create()
                                                   .WithIdentity("trigger_SincronizaCada30seg", "group1")
                                                   .StartNow()
                                                   .WithSimpleSchedule(x => x
                                                                       .WithIntervalInSeconds(30)
                                                                       .RepeatForever())
                                                   .Build();

            scheduler_SincronizaCada30seg.ScheduleJob(job_SincronizaCada30seg, trigger_SincronizaCada30seg);

            ///////////////////  SCHEDULER  //////////////////////////////////
            IScheduler scheduler_LogLlenoCadahora = StdSchedulerFactory.GetDefaultScheduler();

            scheduler_LogLlenoCadahora.Start();
            IJobDetail job_LogLlenoCadahora = JobBuilder.Create <LogLlenoCadahora>().Build();

            ITrigger trigger_LogLlenoCadahora = TriggerBuilder.Create()
                                                .WithIdentity("trigger_LogLlenoCadahora", "group1")
                                                .StartNow()
                                                .WithSimpleSchedule(x => x
                                                                    .WithIntervalInMinutes(60)
                                                                    .RepeatForever())
                                                .Build();

            scheduler_LogLlenoCadahora.ScheduleJob(job_LogLlenoCadahora, trigger_LogLlenoCadahora);
        }
        private void TestMatchers(IScheduler scheduler)
        {
            scheduler.Clear();

            IJobDetail job = JobBuilder.Create <NoOpJob>().WithIdentity("job1", "aaabbbccc").StoreDurably().Build();

            scheduler.AddJob(job, true);
            SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create();
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("trig1", "aaabbbccc").WithSchedule(schedule).ForJob(job).Build();

            scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create <NoOpJob>().WithIdentity("job1", "xxxyyyzzz").StoreDurably().Build();
            scheduler.AddJob(job, true);
            schedule = SimpleScheduleBuilder.Create();
            trigger  = TriggerBuilder.Create().WithIdentity("trig1", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create <NoOpJob>().WithIdentity("job2", "xxxyyyzzz").StoreDurably().Build();
            scheduler.AddJob(job, true);
            schedule = SimpleScheduleBuilder.Create();
            trigger  = TriggerBuilder.Create().WithIdentity("trig2", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            scheduler.ScheduleJob(trigger);

            Collection.ISet <JobKey> jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .AnyGroup());
            Assert.That(jkeys.Count, Is.EqualTo(3), "Wrong number of jobs found by anything matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("xxxyyyzzz"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by equals matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("aaabbbccc"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by equals matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("aa"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by starts with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("xx"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by starts with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("cc"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by ends with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("zzz"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by ends with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("bc"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by contains with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("yz"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by contains with matcher");

            Collection.ISet <TriggerKey> tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .AnyGroup());
            Assert.That(tkeys.Count, Is.EqualTo(3), "Wrong number of triggers found by anything matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("xxxyyyzzz"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by equals matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("aaabbbccc"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by equals matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("aa"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by starts with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("xx"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by starts with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("cc"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by ends with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("zzz"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by ends with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("bc"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by contains with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("yz"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by contains with matcher");
        }
        public void Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
            {
                if (clearJobs)
                {
                    scheduler.Clear();
                }

                if (scheduleJobs)
                {
                    ICalendar cronCalendar    = new CronCalendar("0/5 * * * * ?");
                    ICalendar holidayCalendar = new HolidayCalendar();

                    // QRTZNET-86
                    ITrigger t = scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));
                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    scheduler.AddCalendar("annualCalendar", cal, false, true);

                    IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                    calendarsTrigger.CalendarName = "annualCalendar";

                    JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                    scheduler.ScheduleJob(jd, calendarsTrigger);

                    // QRTZNET-93
                    scheduler.AddCalendar("annualCalendar", cal, true, true);

                    scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);
                    scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);
                    scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);
                    scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);
                    scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);
                    scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                    scheduler.AddCalendar("cronCalendar", cronCalendar, true, true);
                    scheduler.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                    Assert.IsNotNull(scheduler.GetCalendar("annualCalendar"));

                    JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                    lonelyJob.Durable          = true;
                    lonelyJob.RequestsRecovery = true;
                    scheduler.AddJob(lonelyJob, false);
                    scheduler.AddJob(lonelyJob, true);

                    string schedId = scheduler.SchedulerInstanceId;

                    int count = 1;

                    JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = true;
                    IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));
                    trigger.JobDataMap.Add("key", "value");
                    trigger.EndTimeUtc = DateTime.UtcNow.AddYears(10);

                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));
                    Assert.IsNotNull(persisted);
                    Assert.IsTrue(persisted is SimpleTriggerImpl);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                    ct.JobDataMap.Add("key", "value");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    scheduler.ScheduleJob(job, ct);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);

                    var timeZone1 = TimeZoneUtil.FindTimeZoneById("Central European Standard Time");
                    var timeZone2 = TimeZoneUtil.FindTimeZoneById("Mountain Standard Time");

                    DailyTimeIntervalTriggerImpl nt = new DailyTimeIntervalTriggerImpl("nth_trig_" + count, schedId, new TimeOfDay(1, 1, 1), new TimeOfDay(23, 30, 0), IntervalUnit.Hour, 1);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt.TimeZone     = timeZone1;

                    scheduler.ScheduleJob(job, nt);

                    var loadedNt = (IDailyTimeIntervalTrigger)scheduler.GetTrigger(nt.Key);
                    Assert.That(loadedNt.TimeZone.Id, Is.EqualTo(timeZone1.Id));

                    nt.TimeZone = timeZone2;
                    scheduler.RescheduleJob(nt.Key, nt);

                    loadedNt = (IDailyTimeIntervalTrigger)scheduler.GetTrigger(nt.Key);
                    Assert.That(loadedNt.TimeZone.Id, Is.EqualTo(timeZone2.Id));

                    DailyTimeIntervalTriggerImpl nt2 = new DailyTimeIntervalTriggerImpl();
                    nt2.Key          = new TriggerKey("nth_trig2_" + count, schedId);
                    nt2.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt2.JobKey       = job.Key;
                    scheduler.ScheduleJob(nt2);

                    // GitHub issue #92
                    scheduler.GetTrigger(nt2.Key);

                    // GitHub issue #98
                    nt2.StartTimeOfDay = new TimeOfDay(1, 2, 3);
                    nt2.EndTimeOfDay   = new TimeOfDay(2, 3, 4);

                    scheduler.UnscheduleJob(nt2.Key);
                    scheduler.ScheduleJob(nt2);

                    var triggerFromDb = (IDailyTimeIntervalTrigger)scheduler.GetTrigger(nt2.Key);
                    Assert.That(triggerFromDb.StartTimeOfDay.Hour, Is.EqualTo(1));
                    Assert.That(triggerFromDb.StartTimeOfDay.Minute, Is.EqualTo(2));
                    Assert.That(triggerFromDb.StartTimeOfDay.Second, Is.EqualTo(3));

                    Assert.That(triggerFromDb.EndTimeOfDay.Hour, Is.EqualTo(2));
                    Assert.That(triggerFromDb.EndTimeOfDay.Minute, Is.EqualTo(3));
                    Assert.That(triggerFromDb.EndTimeOfDay.Second, Is.EqualTo(4));

                    job.RequestsRecovery = (true);
                    CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl(
                        "calint_trig_" + count,
                        schedId,
                        DateTime.UtcNow.AddMilliseconds(300),
                        DateTime.UtcNow.AddMinutes(1),
                        IntervalUnit.Second,
                        8);
                    intervalTrigger.JobKey = job.Key;

                    scheduler.ScheduleJob(intervalTrigger);

                    // custom time zone
                    const string CustomTimeZoneId = "Custom TimeZone";
                    var          webTimezone      = TimeZoneInfo.CreateCustomTimeZone(
                        CustomTimeZoneId,
                        TimeSpan.FromMinutes(22),
                        null,
                        null);

                    TimeZoneUtil.CustomResolver = id =>
                    {
                        if (id == CustomTimeZoneId)
                        {
                            return(webTimezone);
                        }
                        return(null);
                    };

                    var customTimeZoneTrigger = TriggerBuilder.Create()
                                                .WithIdentity("customTimeZoneTrigger")
                                                .WithCronSchedule("0/5 * * * * ?", x => x.InTimeZone(webTimezone))
                                                .StartNow()
                                                .ForJob(job)
                                                .Build();

                    scheduler.ScheduleJob(customTimeZoneTrigger);
                    var loadedCustomTimeZoneTrigger = (ICronTrigger)scheduler.GetTrigger(customTimeZoneTrigger.Key);
                    Assert.That(loadedCustomTimeZoneTrigger.TimeZone.BaseUtcOffset, Is.EqualTo(TimeSpan.FromMinutes(22)));

                    // bulk operations
                    var        info     = new Dictionary <IJobDetail, Collection.ISet <ITrigger> >();
                    IJobDetail detail   = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    ITrigger   simple   = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    var        triggers = new Collection.HashSet <ITrigger>();
                    triggers.Add(simple);
                    info[detail] = triggers;

                    scheduler.ScheduleJobs(info, true);

                    Assert.IsTrue(scheduler.CheckExists(detail.Key));
                    Assert.IsTrue(scheduler.CheckExists(simple.Key));

                    // QRTZNET-243
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    scheduler.Start();

                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    scheduler.PauseAll();

                    scheduler.ResumeAll();

                    scheduler.PauseJob(new JobKey("job_1", schedId));

                    scheduler.ResumeJob(new JobKey("job_1", schedId));

                    scheduler.PauseJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    Thread.Sleep(TimeSpan.FromSeconds(1));

                    scheduler.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    scheduler.PauseTrigger(new TriggerKey("trig_2", schedId));
                    scheduler.ResumeTrigger(new TriggerKey("trig_2", schedId));

                    scheduler.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.AreEqual(1, scheduler.GetPausedTriggerGroups().Count);

                    Thread.Sleep(TimeSpan.FromSeconds(3));
                    scheduler.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.IsNotNull(scheduler.GetTrigger(new TriggerKey("trig_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_1", schedId)));
                    Assert.IsNotNull(scheduler.GetMetaData());
                    Assert.IsNotNull(scheduler.GetCalendar("weeklyCalendar"));

                    var genericjobKey = new JobKey("genericJob", "genericGroup");
                    var genericJob    = JobBuilder.Create <GenericJobType <string> >()
                                        .WithIdentity(genericjobKey)
                                        .StoreDurably()
                                        .Build();

                    scheduler.AddJob(genericJob, false);

                    genericJob = scheduler.GetJobDetail(genericjobKey);
                    Assert.That(genericJob, Is.Not.Null);
                    scheduler.TriggerJob(genericjobKey);

                    Thread.Sleep(TimeSpan.FromSeconds(20));

                    Assert.That(GenericJobType <string> .TriggeredCount, Is.EqualTo(1));
                    scheduler.Standby();

                    CollectionAssert.IsNotEmpty(scheduler.GetCalendarNames());
                    CollectionAssert.IsNotEmpty(scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId)));

                    CollectionAssert.IsNotEmpty(scheduler.GetTriggersOfJob(new JobKey("job_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_2", schedId)));

                    scheduler.DeleteCalendar("cronCalendar");
                    scheduler.DeleteCalendar("holidayCalendar");
                    scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));
                    scheduler.DeleteJob(job.Key);

                    scheduler.GetJobGroupNames();
                    scheduler.GetCalendarNames();
                    scheduler.GetTriggerGroupNames();

                    TestMatchers(scheduler);
                }
            }
            finally
            {
                scheduler.Shutdown(false);
            }
        }
예제 #14
0
 /// <summary>
 /// 创建trigger
 /// </summary>
 /// <param name="func"></param>
 /// <returns></returns>
 protected ITrigger BuildTrigger(Func <TriggerBuilder, ITrigger> func) => func(TriggerBuilder.Create());
예제 #15
0
        public static async Task Init()
        {
            //调度器
            StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
            IScheduler          scheduler           = await stdSchedulerFactory.GetScheduler();

            await scheduler.Start();

            scheduler.ListenerManager.AddJobListener(new CustomJobListener());
            scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());


            //具体工作
            IJobDetail jobDetail = JobBuilder.Create <SendMessageJob>()
                                   .WithDescription("发送消息调度")
                                   .WithIdentity("sendMessage", "user")
                                   .UsingJobData("id", 100)
                                   .UsingJobData("name", "张三")
                                   .UsingJobData("endDate", "2019-3-21")
                                   .Build();


            //Simple时间策略
            ITrigger trigger = TriggerBuilder.Create()
                               .WithDescription("指定每5秒执行一次")
                               .WithIdentity("5Second", "Second")
                               .WithSimpleSchedule(builder =>
                                                   builder.WithIntervalInSeconds(3)
                                                   .WithRepeatCount(3)
                                                   //.WithMisfireHandlingInstructionFireNow()
                                                   //.WithMisfireHandlingInstructionIgnoreMisfires()
                                                   //.WithMisfireHandlingInstructionNextWithExistingCount()
                                                   //.WithMisfireHandlingInstructionNextWithRemainingCount()
                                                   //.WithMisfireHandlingInstructionNowWithExistingCount()
                                                   //.WithMisfireHandlingInstructionNowWithRemainingCount()

                                                   )
                               .UsingJobData("name1", "小旋风")
                               .Build();

            trigger.JobDataMap.Add("endDate", "2021-3-24");



            //Cron时间策略
            //ITrigger trigger = TriggerBuilder.Create()
            //                               .WithDescription("指定具体时间点执行")
            //                               .WithIdentity("Fixed_Time", "Fixed")
            //                               .WithCronSchedule("0 33 11 * * ?"
            //                                                //,builder => builder
            //                                                //.WithMisfireHandlingInstructionDoNothing()
            //                                                //.WithMisfireHandlingInstructionFireAndProceed()
            //                                                //.WithMisfireHandlingInstructionIgnoreMisfires()
            //                               )
            //                               .Build();



            //await scheduler.ScheduleJob(jobDetail, trigger);

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

            keyValuePairs[jobDetail] = new List <ITrigger>()
            {
                trigger
            };
            await scheduler.ScheduleJobs(keyValuePairs, false);
        }
예제 #16
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(MisfireExample));

            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);

            // statefulJob1 will run every three seconds
            // (but it will delay for ten seconds)
            IJobDetail job = JobBuilder.Create <StatefulDumbJob>()
                             .WithIdentity("statefulJob1", "group1")
                             .UsingJobData(StatefulDumbJob.ExecutionDelay, 10000L)
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(startTime)
                                     .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
                                     .Build();

            DateTimeOffset 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");

            // statefulJob2 will run every three seconds
            // (but it will delay for ten seconds - and therefore purposely misfire after a few iterations)
            job = JobBuilder.Create <StatefulDumbJob>()
                  .WithIdentity("statefulJob2", "group1")
                  .UsingJobData(StatefulDumbJob.ExecutionDelay, 10000L)
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger2", "group1")
                      .StartAt(startTime)
                      .WithSimpleSchedule(x => x
                                          .WithIntervalInSeconds(3)
                                          .RepeatForever()
                                          .WithMisfireHandlingInstructionNowWithExistingCount()) // set misfire instructions
                      .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 ten minutes for triggers to file....
            await Task.Delay(TimeSpan.FromMinutes(10));

            log.Info("------- Shutting Down ---------------------");

            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs.");
        }
예제 #17
0
        /// <summary>
        /// 启动后台计划任务
        /// </summary>
        public static void Start()
        {
            scheduler.GetJobGroupNames();

            /*-------------计划任务代码实现------------------*/
            IJobDetail job;
            ITrigger   trigger;

            //创建任务
            job = Quartz.JobBuilder.Create <RemindJob>().Build();
            //创建触发器
            trigger = TriggerBuilder.Create()
                      .WithIdentity("TimeTrigger", "TimeGroup")
                      .WithSimpleSchedule(t => t.WithIntervalInMinutes(5).RepeatForever())
                      .Build();
            //添加任务及触发器至调度器中
            scheduler.ScheduleJob(job, trigger);


            //创建任务
            //job = Quartz.JobBuilder.Create<MeetSubscribeJob>().Build();
            ////创建触发器
            //trigger = TriggerBuilder.Create()
            //    .WithIdentity("MeetSubscribeJob", "TimeGroup")
            //    .WithSimpleSchedule(t => t.WithIntervalInMinutes(5).RepeatForever())
            //    .Build();
            ////添加任务及触发器至调度器中
            //scheduler.ScheduleJob(job, trigger);

            //每天凌晨1:00获取临床接口的访问数据
            //创建任务
            //job = Quartz.JobBuilder.Create<SyncGuidJob>().Build();
            ////创建触发器
            //string cronExpression2 ="" ;
            //if (string.IsNullOrEmpty(cronExpression2))
            //      cronExpression2 = "0 0 1 * * ? *";
            //    //cronExpression2 = "0 10,15,40 * * * ? ";
            //trigger = TriggerBuilder.Create().WithCronSchedule(cronExpression2).Build();
            ////添加任务及触发器至调度器中
            //scheduler.ScheduleJob(job, trigger);


            //每天凌晨2:00同步费卡文库的科室会
            //job = Quartz.JobBuilder.Create<SyncFkLibMeetingsJob>().Build();
            //string cronExpression = ConfigurationManager.AppSettings["SyncFkLibMeetingsJobCronExpression"];
            //if (string.IsNullOrEmpty(cronExpression)) cronExpression = "0 0 2 ? * *";
            //trigger = TriggerBuilder.Create().WithCronSchedule(cronExpression).Build();
            //scheduler.ScheduleJob(job, trigger);

            //每月1日凌晨1:00同步更新签到人员认证信息到费卡文库
            //job = Quartz.JobBuilder.Create<SyncFkLibUsersJob>().Build();
            ////1.Seconds 秒
            ////2.Minutes 分钟
            ////3.Hours 小时
            ////4.Day - of - Month 月中的天
            ////5.Month 月
            ////6.Day - of - Week 周中的天
            ////7.Year(optional field) 年(可选的域)
            //cronExpression = ConfigurationManager.AppSettings["SyncFkLibUsersJobCronExpression"];
            //if (string.IsNullOrEmpty(cronExpression)) cronExpression = "0 0 1 1 * ?";
            //trigger = TriggerBuilder.Create().WithCronSchedule(cronExpression).Build();
            //scheduler.ScheduleJob(job, trigger);

            /*-------------计划任务代码实现------------------*/

            //启动
            scheduler.Start();
        }
예제 #18
0
        public static void Run(IUnityContainer container)
        {
            // Resolving IScheduler instance
            var scheduler = container.Resolve <IScheduler>();

            #region Triggers

            var fiveMinuteTriggerForever = (ISimpleTrigger)TriggerBuilder.Create()
                                           .WithIdentity("FiveMinuteTriggerForever", AppConstants.DefaultTaskGroup)
                                           .StartNow()
                                           .WithSimpleSchedule(x => x
                                                               .WithIntervalInMinutes(5)
                                                               .RepeatForever())
                                           .Build();

            var twoMinuteTriggerForever = (ISimpleTrigger)TriggerBuilder.Create()
                                          .WithIdentity("TwoMinuteTriggerForever", AppConstants.DefaultTaskGroup)
                                          .StartNow()
                                          .WithSimpleSchedule(x => x
                                                              .WithIntervalInMinutes(2)
                                                              .RepeatForever())
                                          .Build();

            var fifteenSecondsTriggerForever = (ISimpleTrigger)TriggerBuilder.Create()
                                               .WithIdentity("FifteenSecondsTriggerForever", AppConstants.DefaultTaskGroup)
                                               .StartNow()
                                               .WithSimpleSchedule(x => x
                                                                   .WithIntervalInSeconds(15)
                                                                   .RepeatForever())
                                               .Build();

            var sixHourTriggerForever = (ISimpleTrigger)TriggerBuilder.Create()
                                        .WithIdentity("SixHourTriggerForever", AppConstants.DefaultTaskGroup)
                                        .StartNow()
                                        .WithSimpleSchedule(x => x
                                                            .WithIntervalInHours(6)
                                                            .RepeatForever())
                                        .Build();

            #endregion

            #region Send Email Job

            // Send emails every 15 seconds

            var emailJob = JobBuilder.Create <EmailJob>()
                           .WithIdentity("EmailJob", AppConstants.DefaultTaskGroup)
                           .Build();

            scheduler.ScheduleJob(emailJob, fifteenSecondsTriggerForever);

            #endregion

            #region Mark As Solution Job

            // Send mark as solution reminder emails

            var markAsSolutionReminderJob = JobBuilder.Create <MarkAsSolutionReminderJob>()
                                            .WithIdentity("MarkAsSolutionReminderJob", AppConstants.DefaultTaskGroup)
                                            .Build();

            scheduler.ScheduleJob(markAsSolutionReminderJob, sixHourTriggerForever);

            #endregion

            // Starting scheduler
            scheduler.Start();
        }
        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"] = TestConstants.SqlServerConnectionString,
                ["quartz.dataSource.default.provider"]         = TestConstants.DefaultSqlServerProvider,
                ["quartz.serializer.type"]                     = "json"
            };

            // if running SQLite we need this
            // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";

            // 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 ----------------");
        }
예제 #20
0
 private static ITrigger GetTrigger(string cronExpression)
 {
     return(TriggerBuilder.Create()
            .WithCronSchedule(cronExpression)
            .Build());
 }
예제 #21
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(JobStateExample));

            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 ----------------");

            // 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 = await 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 = await 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
            await 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 ---------------------");

            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs.");
        }
예제 #22
0
        private void StartL()
        {
            if (IsRunning)
            {
                return;
            }
            try
            {
                // construct a scheduler factory
                ISchedulerFactory schedFact = new StdSchedulerFactory();

                // get a scheduler, start the schedular before triggers or anything else
                if (sched == null)
                {
                    sched = schedFact.GetScheduler().Result;
                }

                // create job
                IJobDetail job = JobBuilder.Create <SimpleJob>()
                                 .WithIdentity("job1", "group1")
                                 .Build();

                // create trigger

                var triggerB = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1");

                if (StartIn)
                {
                    triggerB =
                        triggerB.StartAt(DateBuilder.FutureDate(
                                             (StartHour * 60 * 60) + (StartMinute * 60) + StartSecond,
                                             IntervalUnit.Second));
                }

                if (StartAt)
                {
                    triggerB =
                        triggerB.StartAt(DateBuilder.DateOf(StartHour, StartMinute, StartSecond, StartDate.Day,
                                                            StartDate.Month, StartDate.Year));
                }
                if (StartDaily)
                {
                    ISet <DayOfWeek> days = new HashSet <DayOfWeek>();
                    if (StartDay0)
                    {
                        days.Add(DayOfWeek.Sunday);
                    }
                    if (StartDay1)
                    {
                        days.Add(DayOfWeek.Monday);
                    }
                    if (StartDay2)
                    {
                        days.Add(DayOfWeek.Tuesday);
                    }
                    if (StartDay3)
                    {
                        days.Add(DayOfWeek.Wednesday);
                    }
                    if (StartDay4)
                    {
                        days.Add(DayOfWeek.Thursday);
                    }
                    if (StartDay5)
                    {
                        days.Add(DayOfWeek.Friday);
                    }
                    if (StartDay6)
                    {
                        days.Add(DayOfWeek.Saturday);
                    }

                    triggerB =
                        triggerB.WithDailyTimeIntervalSchedule(
                            x =>
                            x.WithIntervalInSeconds(TimeBetweenShots)
                            .WithMisfireHandlingInstructionFireAndProceed()
                            .StartingDailyAt(new TimeOfDay(StartHour, StartMinute, StartSecond))
                            .EndingDailyAt(new TimeOfDay(StopHour, StopMinute, StopSecond))
                            .OnDaysOfTheWeek(days)
                            );
                }
                else
                {
                    if (StopAtPhotos)
                    {
                        triggerB =
                            triggerB.WithSimpleSchedule(
                                x =>
                                x.WithIntervalInSeconds(TimeBetweenShots)
                                .WithRepeatCount(StopCaptureCount)
                                .WithMisfireHandlingInstructionNowWithExistingCount());
                    }
                    else if (StopIn)
                    {
                        triggerB =
                            triggerB.WithSimpleSchedule(
                                x =>
                                x.WithIntervalInSeconds(TimeBetweenShots)
                                .WithMisfireHandlingInstructionNowWithExistingCount()
                                .WithRepeatCount(((StopHour * 60 * 60) + (StopMinute * 60) + StopSecond) /
                                                 TimeBetweenShots));
                    }
                    else
                    {
                        triggerB =
                            triggerB.WithSimpleSchedule(
                                x =>
                                x.WithIntervalInSeconds(TimeBetweenShots)
                                .WithMisfireHandlingInstructionNowWithExistingCount()
                                .RepeatForever());
                    }

                    if (StopAt)
                    {
                        triggerB =
                            triggerB.EndAt(DateBuilder.DateOf(StopHour, StopMinute, StopSecond, StopDate.Day,
                                                              StopDate.Month,
                                                              StopDate.Year));
                    }
                }

                trigger = triggerB.Build();


                // Schedule the job using the job and trigger
                sched.ScheduleJob(job, trigger);
                sched.Start();

                if (_bracketingViewModel != null)
                {
                    _bracketingViewModel.Stop();
                }
                _bracketingViewModel = null;
                IsRunning            = true;
                _timeLapseStartTime  = DateTime.Now;
                _lastCaptureTime     = DateTime.Now;
                Log.Debug("Timelapse start");
                _totalCaptures  = 0;
                _timer.Interval = 1000;
                _timer.Start();
                _lastTime = DateTime.Now;
                TimeLapseSettings.Started = true;
                ServiceProvider.Settings.Save(ServiceProvider.Settings.DefaultSession);
            }
            catch (Exception e)
            {
                MessageBox.Show("Unable to start timelapse " + e.Message);
                Log.Debug("Unable to start timelapse ", e);
            }
        }
예제 #23
0
        /// <inheritdoc />
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Queued Hosted Service is running.");
            Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);

            Scheduler.JobFactory = _jobFactory;
            foreach (var dequeueJobSchedule in _dequeueJobSchedules)
            {
                var dequeueJob = JobBuilder.Create(typeof(DequeueJob <>).MakeGenericType(dequeueJobSchedule.WorkItemType))
                                 .StoreDurably()           // this is needed in case of multiple consumers (triggers)
                                 .WithIdentity(name: dequeueJobSchedule.Name, group: JobGroups.InternalJobsGroup)
                                 .SetJobData(new JobDataMap(new Dictionary <string, object> {
                    { JobDataKeys.QueueName, dequeueJobSchedule.Name },
                    { JobDataKeys.PollingInterval, dequeueJobSchedule.PollingInterval },
                    { JobDataKeys.MaxPollingInterval, dequeueJobSchedule.MaxPollingInterval },
                    { JobDataKeys.JobHandlerType, dequeueJobSchedule.JobHandlerType }
                } as IDictionary <string, object>))
                                 .Build();
                await Scheduler.AddJob(dequeueJob, replace : true);

                for (var i = 1; i <= dequeueJobSchedule.InstanceCount; i++)
                {
                    var jobTrigger = TriggerBuilder.Create()
                                     .ForJob(dequeueJob)
                                     .WithIdentity(name: $"{dequeueJobSchedule.Name}{TriggerNames.DequeueJobTrigger}{i}", group: JobGroups.InternalJobsGroup)
                                     .StartNow()
                                     .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMilliseconds(dequeueJobSchedule.PollingInterval + (dequeueJobSchedule.PollingInterval / dequeueJobSchedule.InstanceCount * (i - 1)))).RepeatForever())
                                     .Build();
                    await Scheduler.ScheduleJob(jobTrigger);
                }
                var cleanUpJob = JobBuilder.Create(typeof(DequeuedCleanupJob <>).MakeGenericType(dequeueJobSchedule.WorkItemType))
                                 .StoreDurably()           // This is needed in case of multiple consumers (triggers).
                                 .WithIdentity(name: $"{dequeueJobSchedule.Name}CleanUp", group: JobGroups.InternalJobsGroup)
                                 .SetJobData(new JobDataMap(new Dictionary <string, object> {
                    { JobDataKeys.QueueName, dequeueJobSchedule.Name },
                    { JobDataKeys.CleanUpBatchSize, dequeueJobSchedule.CleanupBatchSize },
                } as IDictionary <string, object>))
                                 .Build();
                await Scheduler.AddJob(cleanUpJob, replace : true);

                var cleanUpTrigger = TriggerBuilder.Create()
                                     .ForJob(cleanUpJob)
                                     .WithIdentity(name: $"{cleanUpJob.Key.Name}Trigger", group: JobGroups.InternalJobsGroup)
                                     .StartNow()
                                     .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(dequeueJobSchedule.CleanupInterval)).RepeatForever())
                                     .Build();
                await Scheduler.ScheduleJob(cleanUpTrigger);
            }
            foreach (var schedule in _scheduledJobSettings)
            {
                var jobDetails = JobBuilder.Create(typeof(ScheduledJob <,>).MakeGenericType(schedule.JobHandlerType, schedule.JobStateType))
                                 .StoreDurably()           // This is needed in case of multiple consumers (triggers).
                                 .WithIdentity(name: schedule.Name, group: schedule.Group ?? JobGroups.InternalJobsGroup)
                                 .WithDescription(schedule.Description)
                                 .SetJobData(new JobDataMap(new Dictionary <string, object> {
                    { JobDataKeys.JobHandlerType, schedule.JobHandlerType }
                } as IDictionary <string, object>))
                                 .Build();
                await Scheduler.AddJob(jobDetails, replace : true);

                var jobTrigger = TriggerBuilder.Create()
                                 .ForJob(jobDetails)
                                 .WithIdentity(name: $"{schedule.Name}.trigger", group: schedule.Group ?? JobGroups.InternalJobsGroup)
                                 .StartNow()
                                 .WithCronSchedule(schedule.CronExpression)
                                 .WithDescription(schedule.CronExpression)
                                 .Build();
                await Scheduler.ScheduleJob(jobTrigger);
            }
            await Scheduler.Start(cancellationToken);
        }
예제 #24
0
        protected virtual void ProcessInternal(string xml)
        {
            PrepForProcessing();

            ValidateXml(xml);
            MaybeThrowValidationException();

            // deserialize as object model
            XmlSerializer            xs   = new XmlSerializer(typeof(QuartzXmlConfiguration20));
            QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml));

            if (data == null)
            {
                throw new SchedulerConfigException("Job definition data from XML was null after deserialization");
            }

            //
            // Extract pre-processing commands
            //
            if (data.preprocessingcommands != null)
            {
                foreach (preprocessingcommandsType command in data.preprocessingcommands)
                {
                    if (command.deletejobsingroup != null)
                    {
                        foreach (string s in command.deletejobsingroup)
                        {
                            string deleteJobGroup = s.NullSafeTrim();
                            if (!String.IsNullOrEmpty(deleteJobGroup))
                            {
                                jobGroupsToDelete.Add(deleteJobGroup);
                            }
                        }
                    }
                    if (command.deletetriggersingroup != null)
                    {
                        foreach (string s in command.deletetriggersingroup)
                        {
                            string deleteTriggerGroup = s.NullSafeTrim();
                            if (!String.IsNullOrEmpty(deleteTriggerGroup))
                            {
                                triggerGroupsToDelete.Add(deleteTriggerGroup);
                            }
                        }
                    }
                    if (command.deletejob != null)
                    {
                        foreach (preprocessingcommandsTypeDeletejob s in command.deletejob)
                        {
                            string name  = s.name.TrimEmptyToNull();
                            string group = s.group.TrimEmptyToNull();

                            if (name == null)
                            {
                                throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified.");
                            }
                            jobsToDelete.Add(new JobKey(name, group));
                        }
                    }
                    if (command.deletetrigger != null)
                    {
                        foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger)
                        {
                            string name  = s.name.TrimEmptyToNull();
                            string group = s.group.TrimEmptyToNull();

                            if (name == null)
                            {
                                throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified.");
                            }
                            triggersToDelete.Add(new TriggerKey(name, group));
                        }
                    }
                }
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands.");
                log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands.");
                log.Debug("Found " + jobsToDelete.Count + " delete job commands.");
                log.Debug("Found " + triggersToDelete.Count + " delete trigger commands.");
            }

            //
            // Extract directives
            //
            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool overWrite = data.processingdirectives[0].overwriteexistingdata;
                log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite);
                OverWriteExistingData = overWrite;
            }
            else
            {
                log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData);
            }

            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates;
                log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates);
                IgnoreDuplicates = ignoreduplicates;
            }
            else
            {
                log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates);
            }

            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger;
                log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative);
                ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative;
            }
            else
            {
                log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger);
            }

            //
            // Extract Job definitions...
            //
            List <jobdetailType> jobNodes = new List <jobdetailType>();

            if (data.schedule != null)
            {
                foreach (var schedule in data.schedule)
                {
                    if (schedule != null)
                    {
                        if (schedule.job != null)
                        {
                            jobNodes.AddRange(schedule.job);
                        }
                    }
                }
            }

            log.Debug("Found " + jobNodes.Count + " job definitions.");

            foreach (jobdetailType jobDetailType in jobNodes)
            {
                string jobName              = jobDetailType.name.TrimEmptyToNull();
                string jobGroup             = jobDetailType.group.TrimEmptyToNull();
                string jobDescription       = jobDetailType.description.TrimEmptyToNull();
                string jobTypeName          = jobDetailType.jobtype.TrimEmptyToNull();
                bool   jobDurability        = jobDetailType.durable;
                bool   jobRecoveryRequested = jobDetailType.recover;

                Type jobType = typeLoadHelper.LoadType(jobTypeName);


                IJobDetail jobDetail = JobBuilder.Create(jobType)
                                       .WithIdentity(jobName, jobGroup)
                                       .WithDescription(jobDescription)
                                       .StoreDurably(jobDurability)
                                       .RequestRecovery(jobRecoveryRequested)
                                       .Build();

                if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null)
                {
                    foreach (entryType entry in jobDetailType.jobdatamap.entry)
                    {
                        string key   = entry.key.TrimEmptyToNull();
                        string value = entry.value.TrimEmptyToNull();
                        jobDetail.JobDataMap.Add(key, value);
                    }
                }

                if (log.IsDebugEnabled)
                {
                    log.Debug("Parsed job definition: " + jobDetail);
                }

                AddJobToSchedule(jobDetail);
            }

            //
            // Extract Trigger definitions...
            //

            List <triggerType> triggerEntries = new List <triggerType>();

            if (data.schedule != null)
            {
                foreach (var schedule in data.schedule)
                {
                    if (schedule != null && schedule.trigger != null)
                    {
                        triggerEntries.AddRange(schedule.trigger);
                    }
                }
            }

            log.Debug("Found " + triggerEntries.Count + " trigger definitions.");

            foreach (triggerType triggerNode in triggerEntries)
            {
                string triggerName        = triggerNode.Item.name.TrimEmptyToNull();
                string triggerGroup       = triggerNode.Item.group.TrimEmptyToNull();
                string triggerDescription = triggerNode.Item.description.TrimEmptyToNull();
                string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull();
                string triggerJobName     = triggerNode.Item.jobname.TrimEmptyToNull();
                string triggerJobGroup    = triggerNode.Item.jobgroup.TrimEmptyToNull();

                int triggerPriority = TriggerConstants.DefaultPriority;
                if (!triggerNode.Item.priority.IsNullOrWhiteSpace())
                {
                    triggerPriority = Convert.ToInt32(triggerNode.Item.priority);
                }

                DateTimeOffset triggerStartTime = SystemTime.UtcNow();
                if (triggerNode.Item.Item != null)
                {
                    if (triggerNode.Item.Item is DateTime)
                    {
                        triggerStartTime = new DateTimeOffset((DateTime)triggerNode.Item.Item);
                    }
                    else
                    {
                        triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item));
                    }
                }

                DateTime?triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?)null;

                IScheduleBuilder sched;

                if (triggerNode.Item is simpleTriggerType)
                {
                    simpleTriggerType simpleTrigger        = (simpleTriggerType)triggerNode.Item;
                    string            repeatCountString    = simpleTrigger.repeatcount.TrimEmptyToNull();
                    string            repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull();

                    int      repeatCount    = ParseSimpleTriggerRepeatCount(repeatCountString);
                    TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString));

                    sched = SimpleScheduleBuilder.Create()
                            .WithInterval(repeatInterval)
                            .WithRepeatCount(repeatCount);

                    if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((SimpleScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction));
                    }
                }
                else if (triggerNode.Item is cronTriggerType)
                {
                    cronTriggerType cronTrigger    = (cronTriggerType)triggerNode.Item;
                    string          cronExpression = cronTrigger.cronexpression.TrimEmptyToNull();
                    string          timezoneString = cronTrigger.timezone.TrimEmptyToNull();

                    TimeZoneInfo tz = timezoneString != null?TimeZoneInfo.FindSystemTimeZoneById(timezoneString) : null;

                    sched = CronScheduleBuilder.CronSchedule(cronExpression)
                            .InTimeZone(tz);

                    if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((CronScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction));
                    }
                }
                else if (triggerNode.Item is calendarIntervalTriggerType)
                {
                    calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType)triggerNode.Item;
                    string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull();

                    IntervalUnit intervalUnit   = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull());
                    int          repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString);

                    sched = CalendarIntervalScheduleBuilder.Create()
                            .WithInterval(repeatInterval, intervalUnit);

                    if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((CalendarIntervalScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction));
                    }
                }
                else
                {
                    throw new SchedulerConfigException("Unknown trigger type in XML configuration");
                }

                IMutableTrigger trigger = (IMutableTrigger)TriggerBuilder.Create()
                                          .WithIdentity(triggerName, triggerGroup)
                                          .WithDescription(triggerDescription)
                                          .ForJob(triggerJobName, triggerJobGroup)
                                          .StartAt(triggerStartTime)
                                          .EndAt(triggerEndTime)
                                          .WithPriority(triggerPriority)
                                          .ModifiedByCalendar(triggerCalendarRef)
                                          .WithSchedule(sched)
                                          .Build();

                if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null)
                {
                    foreach (entryType entry in triggerNode.Item.jobdatamap.entry)
                    {
                        string key   = entry.key.TrimEmptyToNull();
                        string value = entry.value.TrimEmptyToNull();
                        trigger.JobDataMap.Add(key, value);
                    }
                }

                if (log.IsDebugEnabled)
                {
                    log.Debug("Parsed trigger definition: " + trigger);
                }

                AddTriggerToSchedule(trigger);
            }
        }
        /// <summary>
        /// Handles with a given text matches the Expression2 field.
        /// </summary>
        /// <param name="nameValueCollection">A collection of values from the named capture groups.</param>
        /// <param name="results">The results.</param>
        private void Expression2Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results)
        {
            var timesToFire = nameValueCollection.GetValues("TIME");

            var dayOfWeekSpecs = nameValueCollection.GetValues("DAYOFWEEK");
            var monthSpecs     = nameValueCollection.GetValues("MONTH");

            var ordinals = nameValueCollection.GetValues("ORDINAL");

            //init cron values
            List <string> cronExpressions = new List <string>();


            if (timesToFire == null) // if times are not specified assume midnight
            {
                timesToFire = new string[] { "00:00" }
            }
            ;

            foreach (var time in timesToFire)
            {
                DateTime date = DateTime.Today; //default date to today

                if (time != null)
                {
                    date = GrammarHelper.GetTimeFromTimeString(time).Value;
                }

                string cron_sec       = date.Second.ToString();
                string cron_min       = date.Minute.ToString();
                string cron_hour      = date.Hour.ToString();
                string cron_day       = "?";
                string cron_month     = "*";
                string cron_dayofWeek = "*";

                if (monthSpecs != null)
                {
                    var months = GrammarHelper.GetMonthValues(monthSpecs);
                    cron_month = string.Join(",", months.Select(mon => GetMonthCronValue(mon)));
                }

                if (dayOfWeekSpecs != null)
                {
                    var dows = GrammarHelper.GetDayOfWeekValues(dayOfWeekSpecs);
                    cron_dayofWeek = string.Join(",", dows.Select(x => GetDayOfWeekCronValue(x)));
                }

                if (ordinals != null)
                {
                    if (dayOfWeekSpecs != null)
                    {
                        //combine ordinals and dayOfWeeks
                        var combined =
                            from a in GrammarHelper.GetOrdinalValues(ordinals)
                            from b in GrammarHelper.GetDayOfWeekValues(dayOfWeekSpecs)
                            select new { Ordinal = a, DayOfWeek = b };

                        foreach (var item in combined)
                        {
                            cron_dayofWeek  = GetDayOfWeekCronValue(item.DayOfWeek);
                            cron_dayofWeek += GetOrdinalCronValue(item.Ordinal);

                            string cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek }));
                            cronExpressions.Add(cronString);
                        }
                    }

                    if (dayOfWeekSpecs == null) //"day" was specified as DOW, handle special case
                    {
                        //handle special cases
                        cron_dayofWeek = "?";

                        foreach (var o in GrammarHelper.GetOrdinalValues(ordinals))
                        {
                            cron_day = GetOrdinalCronValue(o).Replace("#", "");
                            string cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek }));
                            cronExpressions.Add(cronString);
                        }
                    }
                }
                else //no ordinal was specified
                {
                    string cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek }));
                    cronExpressions.Add(cronString);
                }
            }

            foreach (var cron in cronExpressions)
            {
                var triggerBuilder = TriggerBuilder.Create();

                IScheduleBuilder schedule = CreateScheduleWithCron(cron, timeZone);
                triggerBuilder.WithSchedule(schedule);

                results.Add(triggerBuilder);
            }
        }
예제 #26
0
        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.");
        }
        /// <summary>
        /// Handles with a given text matches the Expression4 field.
        /// </summary>
        /// <param name="nameValueCollection">A collection of values from the named capture groups.</param>
        /// <param name="results">The results.</param>
        private void Expression4Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results)
        {
            // every [n] (days|weeks|months|years) (from [date]) (at [time])

            string amountString   = nameValueCollection["AMOUNT"];
            string intervalString = nameValueCollection["INTERVALUNIT"];

            var dateSpec       = nameValueCollection["DATESPEC"];
            var dayOfWeekSpecs = nameValueCollection.GetValues("DAYOFWEEK");
            var timesToFire    = nameValueCollection.GetValues("TIME");

            DateTime?triggerStartTime = null;

            if (dayOfWeekSpecs != null && GrammarHelper.GetIntervalUnitValueFromString(intervalString) != IntervalUnit.Week)
            {
                throw new Exception("You should only specify a day of the week, when you are using the \"week\" time interval.");
            }

            if (timesToFire == null) // if times are not specified assume midnight
            {
                timesToFire = new string[] { "00:00" }
            }
            ;

            foreach (var timeString in timesToFire)
            {
                if (dateSpec != null || timeString != null)
                {
                    triggerStartTime = GrammarHelper.GetDateTimeFromDateSpecAndTime(dateSpec, timeString);
                }

                if (dayOfWeekSpecs != null)
                {
                    var dayOfWeeks = GrammarHelper.GetDayOfWeekValues(dayOfWeekSpecs);
                    foreach (var dayOfWeek in dayOfWeeks)
                    {
                        if (triggerStartTime == null)
                        {
                            triggerStartTime = SystemTime.Now().DateTime;
                        }

                        DateTime dowTriggerStartTime = triggerStartTime.Value;
                        //seek
                        dowTriggerStartTime = SeekForwardToNextDayOfWeek(dowTriggerStartTime, dayOfWeek);

                        TriggerBuilder triggerBuilder = TriggerBuilder.Create();
                        triggerBuilder.WithSchedule(CreateScheduleWithAmountAndIntervalUnit(amountString, intervalString, timeZone));
                        triggerBuilder.StartAt(new DateTimeOffset(dowTriggerStartTime, timeZone.GetUtcOffset(dowTriggerStartTime)));

                        results.Add(triggerBuilder, null);
                    }
                }
                else
                {
                    TriggerBuilder triggerBuilder = TriggerBuilder.Create();
                    triggerBuilder.WithSchedule(CreateScheduleWithAmountAndIntervalUnit(amountString, intervalString, timeZone));

                    //start on from time
                    if (triggerStartTime != null)
                    {
                        triggerBuilder.StartAt(new DateTimeOffset(triggerStartTime.Value, timeZone.GetUtcOffset(triggerStartTime.Value)));
                    }

                    results.Add(triggerBuilder, null);
                }
            }
        }
예제 #28
0
        public ActionResult Edit(int id, SupervisorUserFieldViewModel supervisorUser)
        {
            try
            {
                // TODO: Add update logic here
                ModelState.Remove("User.firstName");
                ModelState.Remove("User.lastName");
                ModelState.Remove("User.email");
                ModelState.Remove("User.password");
                ModelState.Remove("User.confirmPassword");
                if (ModelState.IsValid)
                {
                    db.Configuration.ValidateOnSaveEnabled = false;
                    var supervisor = db.Supervisor.Where(s => s.recordID == supervisorUser.supervisor.recordID).FirstOrDefault();
                    var user       = db.User.Where(u => u.recordID == supervisorUser.user.recordID).FirstOrDefault();
                    var fields     = new List <Fields>();

                    user.emailNotification = supervisorUser.user.emailNotification;
                    if (supervisorUser.selectedFields != null)
                    {
                        foreach (int item in supervisorUser.selectedFields)
                        {
                            fields.Add(db.Fields.Where(f => f.recordID == item).FirstOrDefault());
                        }
                        supervisor.Fields.Clear();
                        foreach (var item in fields)
                        {
                            supervisor.Fields.Add(item);
                        }
                    }

                    if (supervisorUser.supervisor.daysForReport != null)
                    {
                        supervisor.daysForReport = supervisorUser.supervisor.daysForReport;
                    }

                    db.SaveChanges();

                    //Checking if scheduler is needed
                    if (supervisor.daysForReport != "0")
                    {
                        //Checking for Quartz Scheduler
                        var scheduler = HttpContext.Application["Scheduler"] as IScheduler;

                        //Checking if the job is already added in the scheduler
                        JobKey jobKey    = JobKey.Create("report-job", "report-job-group");
                        var    reportJob = scheduler.GetJobDetail(jobKey);

                        if (reportJob == null)
                        {
                            //Preparing data
                            string subject = "Your Ticketing Report";
                            var    sysUser = db.User.Where(u => u.recordID == 999999).FirstOrDefault();

                            IJobDetail job = JobBuilder.Create <ReportJob>()
                                             .WithIdentity("report-job", "report-job-group")
                                             .Build();
                            job.JobDataMap["subject"] = subject;
                            job.JobDataMap["user"]    = user;
                            job.JobDataMap["sysUser"] = sysUser;

                            ITrigger trigger = TriggerBuilder.Create()
                                               .WithSimpleSchedule(s => s.WithIntervalInSeconds(60).RepeatForever())
                                               .Build();

                            scheduler.ScheduleJob(job, trigger);
                        }
                    }
                }
                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
예제 #29
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            // and start it off
            scheduler.Start();

            // define the job and tie it to our HelloJob class
            var job1 = JobBuilder.Create <HelloJob1>()
                       .WithIdentity("job1", "group1")
                       .RequestRecovery(true)
                       .Build();
            var job2 = JobBuilder.Create <HelloJob2>()
                       .RequestRecovery(true)
                       .WithIdentity("job2", "group1")
                       .Build();
            var job3 = JobBuilder.Create <HelloJob3>()
                       .RequestRecovery(true)
                       .WithIdentity("job3", "group1")
                       .Build();

            // Trigger the job to run now, and then repeat every 10 seconds
            var trigger1 = TriggerBuilder.Create()
                           .StartNow()
                           .WithIdentity("trigger1", "group1")
                           .WithSimpleSchedule(x => x
                                               .WithIntervalInSeconds(10)
                                               .RepeatForever())
                           .Build();
            var trigger2 = TriggerBuilder.Create()
                           .StartNow()
                           .WithIdentity("trigger2", "group1")
                           .WithSimpleSchedule(x => x
                                               .WithIntervalInSeconds(10)
                                               .RepeatForever())
                           .Build();
            var trigger3 = TriggerBuilder.Create()
                           .StartNow()
                           .WithIdentity("trigger3", "group1")
                           .WithSimpleSchedule(x => x
                                               .WithIntervalInSeconds(10)
                                               .RepeatForever())
                           .Build();

            // Tell quartz to schedule the job using our trigger
            try
            {
                scheduler.ScheduleJob(job1, trigger1);
            }
            catch (Exception ex)
            {
                WriteTrace(ex.Message);
            }

            try
            {
                scheduler.ScheduleJob(job2, trigger2);
            }
            catch (Exception ex)
            {
                WriteTrace(ex.Message);
            }

            try
            {
                scheduler.ScheduleJob(job3, trigger3);
            }
            catch (Exception ex)
            {
                WriteTrace(ex.Message);
            }

            // some sleep to show what's happening
            //Thread.Sleep(TimeSpan.FromSeconds(60));

            // and last shut down the scheduler when you are ready to close your program
            //scheduler.Shutdown();
        }
        public async Task Should_Creates_Activity_Event_On_Job_Execution_Exception()
        {
            // Arrange
            Barrier         barrier           = new Barrier(2);
            List <DateTime> jobExecTimestamps = new List <DateTime>();

            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using var tel = Sdk.CreateTracerProviderBuilder()
                            .SetSampler(new AlwaysOnSampler())
                            .AddQuartzInstrumentation(q =>
            {
                q.RecordException = true;
                q.Enrich          = (a, s, p) =>
                {
                    if (s.Equals("OnException"))
                    {
                        throw new Exception("Enrich Exception");
                    }
                };
            })
                            .AddProcessor(activityProcessor.Object)
                            .Build();

            var schedulerConfig = SchedulerBuilder.Create("AUTO", "Scheduler");

            schedulerConfig.UseDefaultThreadPool(x => x.MaxConcurrency = 10);
            var scheduler = await schedulerConfig.BuildScheduler();

            scheduler.Context.Put("BARRIER", barrier);
            scheduler.Context.Put("DATESTAMPS", jobExecTimestamps);
            await scheduler.Start();

            var        testId     = Guid.NewGuid().ToString();
            JobDataMap jobDataMap = new JobDataMap {
                { "TestId", testId }
            };

            var name = Guid.NewGuid().ToString();
            var job  = JobBuilder.Create <TestJobExecutionExceptionJob>()
                       .WithIdentity(name, SchedulerConstants.DefaultGroup)
                       .UsingJobData(jobDataMap)
                       .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(name, SchedulerConstants.DefaultGroup)
                          .StartNow()
                          .Build();

            // Act
            await scheduler.ScheduleJob(job, trigger);

            barrier.SignalAndWait(TimeSpan.FromSeconds(1));

            await scheduler.Shutdown(true);

            // Assert
            Assert.Equal(3, activityProcessor.Invocations.Count);
            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Equal("exception", activity.Events.First().Name);
            Assert.Equal("Quartz.JobExecutionException", activity.Events.First().Tags.SingleOrDefault(t => t.Key.Equals(SemanticConventions.AttributeExceptionType)).Value);
            Assert.Equal("Catch me if you can!", activity.Events.First().Tags.SingleOrDefault(t => t.Key.Equals(SemanticConventions.AttributeExceptionMessage)).Value);
        }