Ejemplo n.º 1
0
        public void TestTriggerFireExclusion()
        {
            sched.Start();
            TestJob.JobHasFired = false;
            JobDetailImpl    myDesc   = new JobDetailImpl("name", "group", typeof(TestJob));
            IOperableTrigger trigger  = new CronTriggerImpl("trigName", "trigGroup", "0/15 * * * * ?");
            AnnualCalendar   calendar = new AnnualCalendar();

            calendar.SetDayExcluded(DateTime.Now, true);
            sched.AddCalendar("calendar", calendar, true, true);
            trigger.CalendarName = "calendar";
            sched.ScheduleJob(myDesc, trigger);
            IOperableTrigger triggerreplace = new CronTriggerImpl("foo", "trigGroup", "name", "group", "0/15 * * * * ?");

            triggerreplace.CalendarName = "calendar";
            sched.RescheduleJob(new TriggerKey("trigName", "trigGroup"), triggerreplace);
            Thread.Sleep(1000 * 20);
            Assert.IsFalse(TestJob.JobHasFired, "task must not be neglected - it is forbidden by the calendar");

            calendar.SetDayExcluded(DateTime.Now, false);
            sched.AddCalendar("calendar", calendar, true, true);
            Thread.Sleep(1000 * 20);
            Assert.IsTrue(TestJob.JobHasFired, "task must be neglected - it is permitted by the calendar");

            sched.DeleteJob(new JobKey("name", "group"));
            sched.DeleteCalendar("calendar");

            sched.Shutdown();
        }
Ejemplo n.º 2
0
 ["annual"] = new CalendarHandler()
 {
     Builder = model =>
     {
         var cal = new AnnualCalendar()
         {
             TimeZone = model.ResolveTimeZone(), Description = model.Description
         };
         foreach (var d in model.Days)
         {
             cal.SetDayExcluded(DateTime.ParseExact(d, "MMMM d", CultureInfo.InvariantCulture), true);
         }
         return(cal);
     },
     Validator = (model, errors) =>
     {
         for (int i = 0; i < model.Days.Count; i++)
         {
             if (DateTime.TryParseExact(model.Days[i], "MMMM d", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _) == false)
             {
                 errors.Add(new ValidationError()
                 {
                     Field = nameof(model.Days), Reason = "Invalid format.", FieldIndex = i
                 });
             }
         }
     }
 },
Ejemplo n.º 3
0
        /// <summary>
        /// AnnualCalendar 排除每年某一天的任务的执行
        /// </summary>
        public static void Fun15()
        {
            var sche = StdSchedulerFactory.GetDefaultScheduler();

            sche.Start();

            AnnualCalendar cale = new AnnualCalendar();

            //12月25号不执行
            cale.SetDayExcluded(new DateTimeOffset(2018, 12, 25, 12, 0, 0, TimeSpan.FromHours(8)), true);
            sche.AddCalendar("myCalendar", cale, true, true);

            var job = JobBuilder.Create <MyJob>()
                      .Build();

            var trigger = TriggerBuilder.Create().StartNow().WithDailyTimeIntervalSchedule(
                m => m.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(7, 0))
                .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(19, 0))
                .WithIntervalInSeconds(1)
                .Build()                                                                                            //是任务在7点-19点间执行,执行频率:每秒执行一次
                )
                          .ModifiedByCalendar("myCalendar")
                          .Build();

            //ModifiedByCalendar 将ICalendar的设置应用到触发器中
            sche.ScheduleJob(job, trigger);
        }
Ejemplo n.º 4
0
        public void SerializeAnnualCalendar()
        {
            var calendar = new AnnualCalendar();

            calendar.Description = "description";
            calendar.SetDayExcluded(DateTime.UtcNow.Date, true);
            CompareSerialization(calendar);
        }
Ejemplo n.º 5
0
        public void TestAnnualCalendarSerialization()
        {
            AnnualCalendar annualCalendar = new AnnualCalendar();
            DateTime       day            = new DateTime(2011, 12, 20, 0, 0, 0);

            annualCalendar.SetDayExcluded(day, true);
            AnnualCalendar clone = annualCalendar.DeepClone();

            Assert.IsTrue(clone.IsDayExcluded(day));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get the object to serialize when generating serialized file for future
        /// tests, and against which to validate deserialized object.
        /// </summary>
        /// <returns></returns>
        protected override object GetTargetObject()
        {
            AnnualCalendar c = new AnnualCalendar();

            c.Description = "description";
            DateTime date = new DateTime(2005, 1, 20, 10, 5, 15);

            c.SetDayExcluded(date, true);
            return(c);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Verify that the target object and the object we just deserialized
        /// match.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="deserialized"></param>
        protected override void VerifyMatch(object target, object deserialized)
        {
            AnnualCalendar targetCalendar       = (AnnualCalendar)target;
            AnnualCalendar deserializedCalendar = (AnnualCalendar)deserialized;

            Assert.IsNotNull(deserializedCalendar);
            Assert.AreEqual(targetCalendar.Description, deserializedCalendar.Description);
            Assert.AreEqual(targetCalendar.DaysExcluded, deserializedCalendar.DaysExcluded);
            //Assert.IsNull(deserializedCalendar.getTimeZone());
        }
Ejemplo n.º 8
0
        private ICalendar CreateCalendar()
        {
            var annualCalendar = new AnnualCalendar();

            foreach (var excludedDate in _holidaysCalendar.ExcludedDates)
            {
                annualCalendar.SetDayExcluded(excludedDate, true);
            }

            return(annualCalendar);
        }
Ejemplo n.º 9
0
        public void AddCalendar_Should_AddTheCalenderToList()
        {
            // Arrange
            var calendar     = new AnnualCalendar();
            var quietPeriods = new QuietPeriods();

            // Act
            quietPeriods.AddCalendar(calendar);

            // Assert
            Assert.Equal(1, quietPeriods.Count);
        }
Ejemplo n.º 10
0
        public void SerializeChainedCalendars()
        {
            var annualCalendar = new AnnualCalendar();

            annualCalendar.Description = "description";
            annualCalendar.SetDayExcluded(DateTime.UtcNow.Date, true);

            var cronCalendar = new CronCalendar("0/5 * * * * ?");

            cronCalendar.CalendarBase = annualCalendar;

            CompareSerialization(cronCalendar);
        }
Ejemplo n.º 11
0
        public void TestDaysExcludedOverTime()
        {
            AnnualCalendar annualCalendar = new AnnualCalendar();

            DateTime day = new DateTime(2005, 6, 23);

            annualCalendar.SetDayExcluded(day, true);

            day = new DateTime(2008, 2, 1);
            annualCalendar.SetDayExcluded(day, true);

            Assert.IsTrue(annualCalendar.IsDayExcluded(day), "The day 1 February is expected to be excluded but it is not");
        }
Ejemplo n.º 12
0
        public async Task RunAsync()
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            #region 添加日历
            AnnualCalendar holidays = new AnnualCalendar(); // 创建一个年度假日日历

            // 元旦 1月1日
            DateTime NewYearDay = new DateTime(DateTime.UtcNow.Year, 1, 1);
            holidays.SetDayExcluded(NewYearDay, true); // true 排除元旦执行  false 在元旦执行

            // 劳动节 5月1日
            DateTime LaborDay = new DateTime(DateTime.UtcNow.Year, 5, 1);
            holidays.SetDayExcluded(LaborDay, true); // true 排除元旦执行  false 在元旦执行

            // 国庆节 10月1日
            DateTime NationalDay = new DateTime(DateTime.UtcNow.Year, 10, 1);
            holidays.SetDayExcluded(NationalDay, true); // true 排除元旦执行  false 在元旦执行

            await scheduler.AddCalendar("holidays", holidays, true, true);

            #endregion

            DateTimeOffset runDate = DateBuilder.DateOf(10, 0, 0, 1, 10);

            IJobDetail job = JobBuilder.Create <HelloJob2>()
                             .WithIdentity("job1", "jobGroup1")
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "triggerGroup1")
                                     .StartAt(runDate)
                                     .WithSimpleSchedule(x => x.WithIntervalInHours(2).RepeatForever())
                                     .ModifiedByCalendar("holidays")
                                     .Build();

            DateTimeOffset df = await scheduler.ScheduleJob(job, trigger);

            ConsoleExtend.WriteLineDebug1($"作业【{job.Key}】 触发器【{trigger.Key}】 将在【{df.LocalDateTime}】执行" +
                                          $",重复执行时间间隔【{trigger.RepeatInterval.Hours}】小时 重复【{trigger.RepeatCount}】次");

            await scheduler.Start();

            Console.WriteLine("等待30秒。。。");
            await Task.Delay(TimeSpan.FromSeconds(30));

            await scheduler.Shutdown(true);

            ConsoleExtend.WriteLineDebug2($"共执行了{(await scheduler.GetMetaData()).NumberOfJobsExecuted}个作业");
        }
Ejemplo n.º 13
0
        public void TestRemoveInTheFuture()
        {
            AnnualCalendar annualCalendar = new AnnualCalendar();

            DateTime day = new DateTime(2005, 6, 23);

            annualCalendar.SetDayExcluded(day, true);

            // Trying to remove the 23th of June
            day = new DateTime(2008, 6, 23);
            annualCalendar.SetDayExcluded(day, false);

            Assert.IsFalse(annualCalendar.IsDayExcluded(day), "The day 23 June is not expected to be excluded but it is");
        }
Ejemplo n.º 14
0
        public async Task TestTriggerFireExclusion()
        {
            await sched.Start();

            TestJob.JobHasFired = false;
            IJobDetail jobDetail = JobBuilder.Create <TestJob>()
                                   .WithIdentity("name", "group")
                                   .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigName", "trigGroup")
                               .ModifiedByCalendar("calendar")
                               .WithCronSchedule("0/15 * * * * ?")
                               .Build();

            AnnualCalendar calendar = new AnnualCalendar();

            calendar.SetDayExcluded(DateTime.Now, true);
            await sched.AddCalendar("calendar", calendar, true, true);

            await sched.ScheduleJob(jobDetail, trigger);

            ITrigger triggerreplace = TriggerBuilder.Create()
                                      .WithIdentity("foo", "trigGroup")
                                      .ForJob(jobDetail)
                                      .ModifiedByCalendar("calendar")
                                      .WithCronSchedule("0/15 * * * * ?")
                                      .Build();

            await sched.RescheduleJob(new TriggerKey("trigName", "trigGroup"), triggerreplace);

            await Task.Delay(TimeSpan.FromSeconds(20));

            Assert.IsFalse(TestJob.JobHasFired, "task must not be neglected - it is forbidden by the calendar");

            calendar.SetDayExcluded(DateTime.Now, false);
            await sched.AddCalendar("calendar", calendar, true, true);

            await Task.Delay(TimeSpan.FromSeconds(20));

            Assert.IsTrue(TestJob.JobHasFired, "task must be neglected - it is permitted by the calendar");

            await sched.DeleteJob(new JobKey("name", "group"));

            await sched.DeleteCalendar("calendar");

            await sched.Shutdown();
        }
Ejemplo n.º 15
0
        public void BaseCalendarShouldNotAffectSettingInternalDataStructures()
        {
            var dayToExclude = new DateTime(2015, 1, 1);

            AnnualCalendar a = new AnnualCalendar();

            a.SetDayExcluded(dayToExclude, true);

            AnnualCalendar b = new AnnualCalendar(a);

            b.SetDayExcluded(dayToExclude, true);

            b.CalendarBase = null;

            Assert.That(b.IsDayExcluded(dayToExclude), "day was no longer excluded after base calendar was detached");
        }
Ejemplo n.º 16
0
        public void ClearCalendar_Should_RemoveAllCalendersFromList()
        {
            // Arrange
            var calendar1 = new AnnualCalendar();
            var calendar2 = new WeeklyCalendar();

            var quietPeriods = new QuietPeriods();

            quietPeriods.AddCalendar(calendar1);
            quietPeriods.AddCalendar(calendar2);

            // Act
            quietPeriods.ClearCalendars();

            // Assert
            Assert.Equal(0, quietPeriods.Count);
        }
Ejemplo n.º 17
0
        public static List <ICalendar> CreateAnnualCalendarsWithSpecifiedDatesExcluded(List <CustomCalendarDefinition> customCalendarDefinitions)
        {
            var actualCalendars = new List <ICalendar>();

            foreach (var customCalendar in customCalendarDefinitions)
            {
                var calendar = new AnnualCalendar
                {
                    Description = customCalendar.CalendarName
                };

                bool shouldExclude = customCalendar.Action.ToLower().Trim() == "exclude";
                foreach (var date in customCalendar.Dates)
                {
                    calendar.SetDayExcluded(date, shouldExclude);
                }

                actualCalendars.Add(calendar);
            }
            return(actualCalendars);
        }
Ejemplo n.º 18
0
        public void TestAnnualCalendarTimeZone()
        {
            TimeZoneInfo   tz = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time");
            AnnualCalendar c  = new AnnualCalendar();

            c.TimeZone = tz;

            DateTime excludedDay = new DateTime(2012, 11, 4, 0, 0, 0);

            c.SetDayExcluded(excludedDay, true);

            // 11/5/2012 12:00:00 AM -04:00  translate into 11/4/2012 11:00:00 PM -05:00 (EST)
            DateTimeOffset date = new DateTimeOffset(2012, 11, 5, 0, 0, 0, TimeSpan.FromHours(-4));

            Assert.IsFalse(c.IsTimeIncluded(date), "date was expected to not be included.");
            Assert.IsTrue(c.IsTimeIncluded(date.AddDays(1)));

            DateTimeOffset expectedNextAvailable = new DateTimeOffset(2012, 11, 5, 0, 0, 0, TimeSpan.FromHours(-5));
            DateTimeOffset actualNextAvailable   = c.GetNextIncludedTimeUtc(date);

            Assert.AreEqual(expectedNextAvailable, actualNextAvailable);
        }
Ejemplo n.º 19
0
        public static void TestQuarz()
        {
            #region 测试验证
            //  Common.Config.PropertiesParser.ReadFromFileResource("test.txt");
            // Run();
            //    Set();
            //     Console.Read();
            #endregion


            //  Quartzlog.LogManager.Adapter=new

            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();  //调度者


            WeeklyCalendar calendar = new WeeklyCalendar();
            calendar.SetDayExcluded(DayOfWeek.Thursday, true);      //设置每周五不能执行;


            HolidayCalendar daycalendar = new HolidayCalendar();
            daycalendar.AddExcludedDate(DateTime.Now);             //只取日   DateTime.Now.Day


            MonthlyCalendar monthcalendar = new MonthlyCalendar();
            monthcalendar.SetDayExcluded(16, true);                //只取月   DateTime.Now.Month

            AnnualCalendar annualCalendar = new AnnualCalendar();
            annualCalendar.SetDayExcluded(DateTime.Now, true);               //只取年月日   DateTime.Now.Year

            CronCalendar cronCalendar = new CronCalendar("* * * 17 6 ?");    //6月17 不执行

            scheduler.AddCalendar("mycalendar", calendar, true, true);       //设置每周五不能执行;
            scheduler.AddCalendar("mycalendar", daycalendar, true, true);    //某一天不执行
            scheduler.AddCalendar("mycalendar", monthcalendar, true, true);  //某每月某一天不执行
            scheduler.AddCalendar("mycalendar", annualCalendar, true, true); //每年某一月某一日不执行

            scheduler.AddCalendar("mycalendar", cronCalendar, true, true);   //每年某一月某一日不执行



            scheduler.Start();
            var job = JobBuilder.Create <LxshJob>().WithDescription("Job")
                      .WithIdentity("lxshJob", "lxshGroup")
                      .UsingJobData("userName", "Joblxsh")
                      .Build();                             //任务

            var job1 = JobBuilder.Create <LxshJob>().WithDescription("Job")
                       .WithIdentity("lxshJob", "lxshGroup")
                       .UsingJobData("userName", "Joblxsh1")
                       .Build();                        //任务

            var trigger = TriggerBuilder.Create().StartNow()
                          .WithDescription("trigger")
                          .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).WithRepeatCount(10))
                          // .WithCalendarIntervalSchedule(x=>x.WithIntervalInYears(1))
                          //   .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever())
                          .WithDailyTimeIntervalSchedule(x =>
            {
                x.OnDaysOfTheWeek(new DayOfWeek[2] {
                    DayOfWeek.Tuesday, DayOfWeek.Friday
                });                                                   //每周二或者周五执行
                x.OnEveryDay()
                .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(8, 00)) //   八点开始
                .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(18, 00))  //    十八点开始
                .WithIntervalInSeconds(1);                            // 每1s执行一次
            })
                                                                      // .ModifiedByCalendar("mycalendar")
                          .Build();
            //秒分时日月
            var trigger1 = TriggerBuilder.Create().WithCronSchedule("* * * * * ?").Build();       //1秒执行一次
            var trigger2 = TriggerBuilder.Create().WithCronSchedule("0 * * * * ?").Build();       //1分钟执行一次
            var trigger3 = TriggerBuilder.Create().WithCronSchedule("0 0/30 8-20 * * ?").Build(); //30分钟检查一次 8-20点
            var trigger4 = TriggerBuilder.Create().WithCronSchedule("* * * * * ?").Build();

            // scheduler.ListenerManager.AddJobListener(new lxshJobLinstener(), GroupMatcher<JobKey>.AnyGroup());

            scheduler.ScheduleJob(job, trigger);  //开始调度任务
                                                  //    scheduler.GetTriggersOfJob(new JobKey("lxshJob")).Select(x =>x.Key.ToString() );
            Console.Read();

            #region WithCronSchedule
            //           --------------------------------------
            //   0 0 12 * * ? 每天12点触发

            //   0 15 10 ? **每天10点15分触发

            //   0 15 10 * * ? 每天10点15分触发

            //   0 15 10 * * ? *每天10点15分触发

            //   0 15 10 * * ? 2005 2005年每天10点15分触发

            // 0 * 14 * * ? 每天下午的 2点到2点59分每分触发

            // 0 0 / 5 14 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发)

            // 0 0 / 5 14,18 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发) 每天下午的 18点到18点59分(整点开始,每隔5分触发)

            // 0 0 - 5 14 * * ? 每天下午的 2点到2点05分每分触发

            // 0 10,44 14 ? 3 WED 3月分每周三下午的 2点10分和2点44分触发

            // 0 15 10 ? *MON - FRI 从周一到周五每天上午的10点15分触发

            // 0 15 10 15 * ? 每月15号上午10点15分触发

            // 0 15 10 L * ? 每月最后一天的10点15分触发

            // 0 15 10 ? *6L 每月最后一周的星期五的10点15分触发

            // 0 15 10 ? *6L 2002 - 2005 从2002年到2005年每月最后一周的星期五的10点15分触发

            // 0 15 10 ? *6#3         每月的第三周的星期五开始触发
            //    0 0 12 1 / 5 * ? 每月的第一个中午开始每隔5天触发一次

            // 0 11 11 11 11 ? 每年的11月11号 11点11分触发(光棍节)
            //--------------------------------------


            #endregion
        }
Ejemplo n.º 20
0
        public async Task Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
            {
                if (clearJobs)
                {
                    await scheduler.Clear();
                }

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

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

                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    await 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));
                    await scheduler.ScheduleJob(jd, calendarsTrigger);

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

                    await scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);

                    await scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);

                    await scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);

                    await scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);

                    await scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);

                    await scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

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

                    await 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;
                    await scheduler.AddJob(lonelyJob, false);

                    await 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);
                    await scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = await 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);
                    await 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);
                    await 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);
                    await 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));
                    await 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);

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

                    await scheduler.ScheduleJob(job, nt);

                    var loadedNt = (IDailyTimeIntervalTrigger)await scheduler.GetTrigger(nt.Key);

                    Assert.That(loadedNt.TimeZone.Id, Is.EqualTo(timeZone1.Id));

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

                    loadedNt = (IDailyTimeIntervalTrigger)await 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;
                    await scheduler.ScheduleJob(nt2);

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

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

                    await scheduler.UnscheduleJob(nt2.Key);

                    await scheduler.ScheduleJob(nt2);

                    var triggerFromDb = (IDailyTimeIntervalTrigger)await 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;

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

                    await scheduler.ScheduleJob(customTimeZoneTrigger);

                    var loadedCustomTimeZoneTrigger = (ICronTrigger)await scheduler.GetTrigger(customTimeZoneTrigger.Key);

                    Assert.That(loadedCustomTimeZoneTrigger.TimeZone.BaseUtcOffset, Is.EqualTo(TimeSpan.FromMinutes(22)));

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

                    await scheduler.ScheduleJobs(info, true);

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

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

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    await scheduler.Start();

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await scheduler.PauseAll();

                    await scheduler.ResumeAll();

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

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

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

                    await Task.Delay(TimeSpan.FromSeconds(1));

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

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

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

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

                    var pausedTriggerGroups = await scheduler.GetPausedTriggerGroups();

                    Assert.AreEqual(1, pausedTriggerGroups.Count);

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await 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");
                    GenericJobType.Reset();
                    var genericJob = JobBuilder.Create <GenericJobType>()
                                     .WithIdentity(genericjobKey)
                                     .StoreDurably()
                                     .Build();

                    await scheduler.AddJob(genericJob, false);

                    genericJob = await scheduler.GetJobDetail(genericjobKey);

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

                    GenericJobType.WaitForTrigger(TimeSpan.FromSeconds(20));

                    Assert.That(GenericJobType.TriggeredCount, Is.EqualTo(1));
                    await scheduler.Standby();

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

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

                    await scheduler.DeleteCalendar("cronCalendar");

                    await scheduler.DeleteCalendar("holidayCalendar");

                    await scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));

                    await scheduler.DeleteJob(job.Key);

                    await scheduler.GetJobGroupNames();

                    await scheduler.GetCalendarNames();

                    await scheduler.GetTriggerGroupNames();

                    await TestMatchers(scheduler);
                }
            }
            finally
            {
                await scheduler.Shutdown(false);
            }
        }
Ejemplo n.º 21
0
        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);
                    NthIncludedDayTrigger nt = new NthIncludedDayTrigger("nth_trig_" + count, schedId);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt.N            = 1;

                    scheduler.ScheduleJob(job, nt);

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

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

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

                    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();
                }
            }
            finally
            {
                scheduler.Shutdown(false);
            }
        }
Ejemplo n.º 22
0
 public AnnualCalendarDto(AnnualCalendar calendar) : base(calendar)
 {
     DaysExcluded = calendar.DaysExcluded;
     TimeZone     = new TimeZoneDto(calendar.TimeZone);
 }
Ejemplo n.º 23
0
 public void Setup()
 {
     cal          = new AnnualCalendar();
     cal.TimeZone = TimeZoneInfo.Utc; //assume utc if not specified.
 }
Ejemplo n.º 24
0
        public async Task Test(IScheduler[] schedulers, bool clearJobs, bool scheduleJobs)
        {
            var scheduler = schedulers[0];

            try
            {
                if (clearJobs)
                {
                    foreach (var s in schedulers)
                    {
                        await s.Clear();
                    }
                }

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

                    // QRTZNET-86
                    var t = await scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));

                    (t).Should().BeNull();

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

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

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

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

                    await scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);

                    await scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);

                    await scheduler.AddCalendar("dailyCalendar",
                                                new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);

                    await scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);

                    await scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);

                    await scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

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

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

                    (await scheduler.GetCalendar("annualCalendar")).Should().NotBeNull();

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

                    await scheduler.AddJob(lonelyJob, true);

                    var schedId = scheduler.SchedulerInstanceId;

                    var count = 1;

                    var 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.UtcNow.AddMilliseconds(1000L);
                    await scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    var persisted = await scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));

                    (persisted).Should().NotBeNull();
                    (persisted is SimpleTriggerImpl).Should().BeTrue();

                    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.UtcNow.AddMilliseconds(2000L);
                    await 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.UtcNow.AddMilliseconds(1000L);
                    await 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.UtcNow.AddMilliseconds(1000L);
                    await 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));
                    await 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.UtcNow.AddMilliseconds(1000);

                    await 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 nt = new DailyTimeIntervalTriggerImpl("nth_trig_" + count, schedId, new TimeOfDay(1, 1, 1),
                                                              new TimeOfDay(23, 30, 0), IntervalUnit.Hour, 1);
                    nt.StartTimeUtc = DateTime.UtcNow.Date.AddMilliseconds(1000);

                    await scheduler.ScheduleJob(job, nt);

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

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

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

                    await scheduler.UnscheduleJob(nt2.Key);

                    await scheduler.ScheduleJob(nt2);

                    var triggerFromDb = (IDailyTimeIntervalTrigger)await scheduler.GetTrigger(nt2.Key);

                    triggerFromDb.StartTimeOfDay.Hour.Should().Be(1);
                    triggerFromDb.StartTimeOfDay.Minute.Should().Be(2);
                    triggerFromDb.StartTimeOfDay.Second.Should().Be(3);

                    triggerFromDb.EndTimeOfDay.Hour.Should().Be(2);
                    triggerFromDb.EndTimeOfDay.Minute.Should().Be(3);
                    triggerFromDb.EndTimeOfDay.Second.Should().Be(4);

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

                    await scheduler.ScheduleJob(intervalTrigger);

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

                    await scheduler.ScheduleJobs(info, true);

                    (await scheduler.CheckExists(detail.Key)).Should().BeTrue();
                    (await scheduler.CheckExists(simple.Key)).Should().BeTrue();

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

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    foreach (var s in schedulers)
                    {
                        await s.Start();
                    }

                    await Task.Delay(3 *schedulers.Length);

                    await scheduler.PauseAll();

                    await scheduler.ResumeAll();

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

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

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

                    await Task.Delay(TimeSpan.FromSeconds(1));

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

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

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

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

                    (await scheduler.GetPausedTriggerGroups()).Count.Should().Be(1);

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await scheduler.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    (await scheduler.GetTrigger(new TriggerKey("trig_2", schedId))).Should().NotBeNull();
                    (await scheduler.GetJobDetail(new JobKey("job_1", schedId))).Should().NotBeNull();
                    (await scheduler.GetMetaData()).Should().NotBeNull();
                    (await scheduler.GetCalendar("weeklyCalendar")).Should().NotBeNull();

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

                    await scheduler.AddJob(genericJob, false);

                    genericJob = await scheduler.GetJobDetail(genericjobKey);

                    genericJob.Should().NotBeNull();
                    await scheduler.TriggerJob(genericjobKey);

                    await Task.Delay(TimeSpan.FromSeconds(30));

                    GenericJobType <string> .TriggeredCount.Should().Be(1);

                    await scheduler.Standby();

                    (await scheduler.GetCalendarNames()).Should().NotBeEmpty();
                    (await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId))).Should().NotBeEmpty();
                    (await scheduler.GetTriggersOfJob(new JobKey("job_2", schedId))).Should().NotBeEmpty();
                    (await scheduler.GetJobDetail(new JobKey("job_2", schedId))).Should().NotBeNull();

                    await scheduler.DeleteCalendar("cronCalendar");

                    await scheduler.DeleteCalendar("holidayCalendar");

                    await scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));

                    await scheduler.DeleteJob(job.Key);

                    await scheduler.GetJobGroupNames();

                    await scheduler.GetCalendarNames();

                    await scheduler.GetTriggerGroupNames();

                    await TestMatchers(scheduler);
                }
            }
            finally
            {
                foreach (var s in schedulers)
                {
                    await s.Shutdown(false);
                }
            }
        }
Ejemplo n.º 25
0
 public AnnualCalendarDto(AnnualCalendar calendar, string calendarName) : base(calendar, calendarName)
 {
     DaysExcluded = calendar.DaysExcluded;
     TimeZone     = new TimeZoneDto(calendar.TimeZone);
 }
Ejemplo n.º 26
0
 public void Setup()
 {
     cal = new AnnualCalendar();
 }
Ejemplo n.º 27
0
        private void RunAdoJobStoreTest(string dbProvider, string connectionStringId,
                                        NameValueCollection extraProperties)
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"]      = "TestScheduler";
            properties["quartz.scheduler.instanceId"]        = "instance_one";
            properties["quartz.threadPool.type"]             = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]      = "10";
            properties["quartz.threadPool.threadPriority"]   = "Normal";
            properties["quartz.jobStore.misfireThreshold"]   = "60000";
            properties["quartz.jobStore.type"]               = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
            properties["quartz.jobStore.useProperties"]      = "false";
            properties["quartz.jobStore.dataSource"]         = "default";
            properties["quartz.jobStore.tablePrefix"]        = "QRTZ_";
            properties["quartz.jobStore.clustered"]          = clustered.ToString();

            if (extraProperties != null)
            {
                foreach (string key in extraProperties.Keys)
                {
                    properties[key] = extraProperties[key];
                }
            }

            if (connectionStringId == "SQLServer" || connectionStringId == "SQLite")
            {
                // if running MS SQL Server we need this
                properties["quartz.jobStore.lockHandler.type"] =
                    "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";
            }

            string connectionString;

            if (!dbConnectionStrings.TryGetValue(connectionStringId, out connectionString))
            {
                throw new Exception("Unknown connection string id: " + connectionStringId);
            }
            properties["quartz.dataSource.default.connectionString"] = connectionString;
            properties["quartz.dataSource.default.provider"]         = dbProvider;

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

            try
            {
                if (clearJobs)
                {
                    CleanUp(sched);
                }

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

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

                    AnnualCalendar cal = new AnnualCalendar();
                    sched.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));
                    sched.ScheduleJob(jd, calendarsTrigger);

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

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

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

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

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

                    string schedId = sched.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.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    sched.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = sched.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));
                    sched.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));
                    sched.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));
                    sched.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));
                    sched.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.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    sched.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);
                    NthIncludedDayTrigger nt = new NthIncludedDayTrigger("cron_trig_" + count, schedId);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt.N            = 1;

                    sched.ScheduleJob(job, nt);

                    sched.Start();

                    sched.PauseAll();

                    sched.ResumeAll();

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

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

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

                    Thread.Sleep(1000);

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

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

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

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

                    Thread.Sleep(1000);
                    sched.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));


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

                    sched.Standby();

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

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

                    sched.DeleteCalendar("cronCalendar");
                    sched.DeleteCalendar("holidayCalendar");
                    sched.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));
                }
            }
            finally
            {
                sched.Shutdown(false);
            }
        }
Ejemplo n.º 28
0
 public void Setup()
 {
     cal          = new AnnualCalendar();
     cal.TimeZone = TestTimeZone;
 }
Ejemplo n.º 29
0
 static void InitializeAnnual(AnnualCalendar annualCalendar, IAnnualCalendar calendar)
 {
     annualCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone));
     calendar.DatesExcluded.ForEach(time => annualCalendar.SetDayExcluded(time, true));
     calendar.DatesIncluded.ForEach(time => annualCalendar.SetDayExcluded(time, false));
 }
Ejemplo n.º 30
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(CalendarExample));

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

            // Add the holiday calendar to the schedule
            AnnualCalendar holidays = new AnnualCalendar();

            // fourth of July (July 4)
            DateTime fourthOfJuly = new DateTime(DateTime.UtcNow.Year, 7, 4);

            holidays.SetDayExcluded(fourthOfJuly, true);

            // halloween (Oct 31)
            DateTime halloween = new DateTime(DateTime.UtcNow.Year, 10, 31);

            holidays.SetDayExcluded(halloween, true);

            // christmas (Dec 25)
            DateTime christmas = new DateTime(DateTime.UtcNow.Year, 12, 25);

            holidays.SetDayExcluded(christmas, true);

            // tell the schedule about our holiday calendar
            await sched.AddCalendar("holidays", holidays, false, false);

            // schedule a job to run hourly, starting on halloween
            // at 10 am

            DateTimeOffset runDate = DateBuilder.DateOf(0, 0, 10, 31, 10);

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

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(runDate)
                                     .WithSimpleSchedule(x => x.WithIntervalInHours(1).RepeatForever())
                                     .ModifiedByCalendar("holidays")
                                     .Build();

            // schedule the job and print the first run date
            DateTimeOffset firstRunTime = await sched.ScheduleJob(job, trigger);

            // print out the first execution date.
            // Note:  Since Halloween (Oct 31) is a holiday, then
            // we will not run until the next day! (Nov 1)
            log.Info($"{job.Key} will run at: {firstRunTime:r} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds");

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            log.Info("------- Starting Scheduler ----------------");
            await sched.Start();

            // wait 30 seconds:
            // note:  nothing will run
            log.Info("------- Waiting 30 seconds... --------------");

            // wait 30 seconds to show jobs
            await Task.Delay(TimeSpan.FromSeconds(30));

            // executing...

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

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

            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs.");
        }