Example #1
0
        /// <summary>
        /// HolidayCalendar 排除某一天的任务的执行(如果涉及到同一天跨年的情况,需要多次添加不同年份)
        /// </summary>
        public static void Fun13()
        {
            var sche = StdSchedulerFactory.GetDefaultScheduler();

            sche.Start();

            HolidayCalendar cale = new HolidayCalendar();

            cale.AddExcludedDate(DateTime.Now.AddYears(-1)); //排除去年的今天不处理
            cale.AddExcludedDate(DateTime.Now);              //排除今天不处理
            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);
        }
Example #2
0
        private static async Task ScheduleSayHelloJob(IScheduler scheduler)
        {
            //创建作业和触发器
            var jobDetail = JobBuilder.Create <SayHelloJob>()
                            .SetJobData(new JobDataMap()
            {
                new KeyValuePair <string, object>("UserName", "Tom"),
                new KeyValuePair <string, object>("RunSuccess", false)
            })
                            .WithIdentity("SayHelloJob-Tom", "DemoGroup")
                            .RequestRecovery(true)
                            .StoreDurably(true)
                            .Build();

            var calandar = new HolidayCalendar();

            calandar.AddExcludedDate(DateTime.Today);

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

            var trigger = TriggerBuilder.Create()
                          .WithCronSchedule("*/1 * * * * ?")
                          //.ModifiedByCalendar("holidayCalendar")
                          .Build();

            //添加调度
            await scheduler.ScheduleJob(jobDetail, trigger);
        }
Example #3
0
        static async void ThridTriggers()
        {
            //构造一个策略工厂
            //NameValueCollection props = new NameValueCollection {
            //    {"quartz.serializer.type","binary" }
            //};

            HolidayCalendar cal = new HolidayCalendar();

            cal.AddExcludedDate(DateTime.Now);

            StdSchedulerFactory factory = new StdSchedulerFactory();
            //获取一个策略
            IScheduler sched = await factory.GetScheduler();

            await sched.AddCalendar("myholiday", cal, false, false);

            //开始策略
            await sched.Start();

            //设置一个任务
            IJobDetail job = JobBuilder.Create <DumbJob>().WithIdentity("myjob", "group1").UsingJobData("jobSays", "Hello world!").UsingJobData("myFloatValue", 3.1415f).Build();
            //设置任务触发条件
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("myTrigger", "group1").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever()).ModifiedByCalendar("myholiday").Build();
            //将任务加入任务列表
            await sched.ScheduleJob(job, trigger);
        }
Example #4
0
        private static ICalendar GetCalendar()
        {
            var bankHolidayCalendar = new HolidayCalendar();

            bankHolidayCalendar.AddExcludedDate(DateTime.Today.AddDays(1));
            return(bankHolidayCalendar);
        }
        public void ShouldAddExclusionDatesToExistingHolidayCalendar()
        {
            // Arrange
            Guid         calId          = Guid.NewGuid();
            const string calName        = "TestHolCal";
            var          exclusionDate1 = new DateTime(2016, 01, 01);
            var          exclusionDate2 = new DateTime(2016, 01, 02);

            _mockPersistanceStore.Setup(m => m.GetCalendarName(calId)).Returns(calName);

            var registeredCalendar = new HolidayCalendar();

            registeredCalendar.AddExcludedDate(exclusionDate1);
            _mockScheduler.Setup(i => i.GetCalendar(calName)).Returns(registeredCalendar);

            ISchedulerCore schedulerCore = new SchedulerCore(_mockScheduler.Object, _mockPersistanceStore.Object);

            // Act
            schedulerCore.AddHolidayCalendarExclusionDates(calId, new List <DateTime> {
                exclusionDate1, exclusionDate2
            });

            // Assert
            _mockScheduler.Verify(
                x => x.AddCalendar(calName,
                                   It.Is <HolidayCalendar>(
                                       c => c.ExcludedDates.Contains(exclusionDate1) && c.ExcludedDates.Contains(exclusionDate2) &&
                                       c.ExcludedDates.Count == 2), true, true), Times.Once);
        }
Example #6
0
        /// <summary>
        /// Register new <see cref="HolidayCalendar"/> and optionally provide an initital set of dates to exclude.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <param name="daysExcludedUtc"></param>
        public Guid AddHolidayCalendar(string name, string description, IList <DateTime> daysExcludedUtc = null)
        {
            var holidays = new HolidayCalendar {
                Description = description
            };

            if (null != daysExcludedUtc && daysExcludedUtc.Count > 0)
            {
                foreach (var dateTime in daysExcludedUtc)
                {
                    holidays.AddExcludedDate(dateTime);
                }
            }

            Guid id;

            using (var tran = new TransactionScope())
            {
                id = _persistanceStore.UpsertCalendarIdMap(name);
                _scheduler.AddCalendar(name, holidays, true, true);
                tran.Complete();
            }

            return(id);
        }
Example #7
0
        public void SerializeHolidayCalendar()
        {
            var calendar = new HolidayCalendar();

            calendar.Description = "description";
            calendar.AddExcludedDate(DateTime.UtcNow.Date);
            CompareSerialization(calendar);
        }
Example #8
0
        public void TestHolidayCalendarSerialization()
        {
            HolidayCalendar holidayCalendar = new HolidayCalendar();

            holidayCalendar.AddExcludedDate(new DateTime(2010, 1, 20));
            HolidayCalendar clone = holidayCalendar.DeepClone();

            Assert.AreEqual(1, clone.ExcludedDates.Count);
        }
Example #9
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()
        {
            HolidayCalendar c = new HolidayCalendar();

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

            c.AddExcludedDate(date);
            return(c);
        }
Example #10
0
        public override ICalendar GetCalendar()
        {
            var cal = new HolidayCalendar();

            cal.TimeZone = TimeZoneInfo.Local;

            foreach (var d in this.Dates)
            {
                cal.AddExcludedDate(d);
            }
            return(cal);
        }
Example #11
0
        private void btnTest1_Click(object sender, EventArgs e)
        {
            HolidayCalendar cal = new HolidayCalendar();

            cal.AddExcludedDate(DateTime.UtcNow);

            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();

            sched.AddCalendar("myHolidays", cal, false, false);


            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("myJob", "group1")
                             .Build();

            ITrigger t = TriggerBuilder.Create()
                         .WithIdentity("myTrigger")
                         .ForJob("myJob")
                         .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(9, 30)) // execute job daily at 9:30
                         .ModifiedByCalendar("myHolidays")                              // but not on holidays
                         .Build();

            // .. schedule job with trigger


            // define the job and tie it to our HelloJob class
            IJobDetail job2 = JobBuilder.Create <HelloJob>()
                              .WithIdentity("myJob2", "group1")
                              .Build();



            ITrigger t2 = TriggerBuilder.Create()
                          .WithIdentity("myTrigger2")
                          .ForJob("myJob2")
                          .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(11, 30)) // execute job daily at 11:30
                          .ModifiedByCalendar("myHolidays")                               // but not on holidays
                          .Build();


            // .. schedule job with trigger2



            sched.ScheduleJob(job, t);
            sched.ScheduleJob(job, t2);
        }
Example #12
0
        /// <summary>
        /// Register new <see cref="HolidayCalendar"/> and optionally provide an initital set of dates to exclude.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <param name="daysExcludedUtc"></param>
        public void AddHolidayCalendar(string name, string description, IList <DateTime> daysExcludedUtc = null)
        {
            var holidays = new HolidayCalendar();

            holidays.Description = description;

            if (null != daysExcludedUtc && daysExcludedUtc.Count > 0)
            {
                foreach (var dateTime in daysExcludedUtc)
                {
                    holidays.AddExcludedDate(dateTime);
                }
            }

            _scheduler.AddCalendar(name, holidays, true, true);
        }
Example #13
0
        public async Task RunMain()
        {
            HolidayCalendar cal      = new HolidayCalendar();
            DateTime        someDate = DateTime.Now.AddDays(2);

            cal.AddExcludedDate(someDate);
            // construct a scheduler factory
            NameValueCollection props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);

            // get a scheduler
            IScheduler sched = await factory.GetScheduler();

            await sched.AddCalendar("myHolidays", cal, false, false);

            ITrigger t = TriggerBuilder.Create()
                         .WithIdentity("myTrigger")
                         .ForJob("myJob")
                         .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(9, 30)) // execute job daily at 9:30
                         .ModifiedByCalendar("myHolidays")                              // but not on holidays
                         .Build();

            // define the job and tie it to our DumbJob class
            IJobDetail job = JobBuilder.Create <DumbJob>()
                             .WithIdentity("myJob", "group1") // name "myJob", group "group1"
                             .UsingJobData("jobSays", "Hello World!")
                             .UsingJobData("myFloatValue", 3.141f)
                             .UsingJobData("guid", Guid.NewGuid().ToString())
                             .Build();

            await sched.ScheduleJob(job, t);

            ITrigger t2 = TriggerBuilder.Create()
                          .WithIdentity("myTrigger2")
                          .ForJob("myJob2")
                          .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(11, 30)) // execute job daily at 11:30
                          .ModifiedByCalendar("myHolidays")                               // but not on holidays
                          .Build();

            // .. schedule job with trigger2
            await sched.ScheduleJob(job, t2);
        }
Example #14
0
        /// <summary>
        /// 演示日历功能的使用
        /// </summary>
        private static void CalendarDemo()
        {
            string holiday = "我的假期";

            DateTime newYear = new DateTime(DateTime.UtcNow.Year, 1, 1);

            HolidayCalendar cal = new HolidayCalendar();

            cal.AddExcludedDate(newYear);
            CurrentSched.AddCalendar(holiday, cal, false, false);

            IJobDetail calJob = JobBuilder.Create <SimpleJob>().WithIdentity("日历任务名称", "日历任务组名").Build();    //创建一个日历任务

            ITrigger calTrigger = TriggerBuilder.Create().WithIdentity("触发器名称", "触发器组名").StartNow()
                                  .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(14, 13)).ModifiedByCalendar(holiday).Build(); //每天上午9:30分执行,但新年的第1天不执行

            CurrentSched.ScheduleJob(calJob, calTrigger);
        }
Example #15
0
        protected override void OnStart(string[] args)
        {
            logger.Log(LogLevel.Info, String.Format("Starting NACHA File Processor"));

            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            IScheduler sched = schedFact.GetScheduler();
            Context    ctx   = new Context();

            //Get Holiday Calendar Days to Not Generate NACHA File
            HolidayCalendar cal      = new HolidayCalendar();
            var             calendar = ctx.Calendars.FirstOrDefault(c => c.CalendarCode == "NACHAHolidayCalendar");

            foreach (var calendarDate in calendar.CalendarDates)
            {
                cal.AddExcludedDate(calendarDate.SelectedDate);
            }
            sched.AddCalendar("myHolidays", cal, true, true);

            JobDetail jobDetail = new JobDetail("myJob", null, typeof(CreateNachaFileJob));

            //Setup trigger for NACHA file generation at 8:00 PM
            //Trigger trigger = TriggerUtils.MakeImmediateTrigger(100, new TimeSpan(0, 20, 0));
            Trigger trigger = TriggerUtils.MakeDailyTrigger(22, 00);

            trigger.StartTimeUtc = DateTime.UtcNow;
            trigger.Name         = "myTrigger2";
            //trigger.CalendarName = "myHolidays";
            sched.ScheduleJob(jobDetail, trigger);

            try
            {
                logger.Log(LogLevel.Info, String.Format("Starting Scheduler"));
                sched.Start();
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Info, String.Format("Exception Starting Scheduler {0}", ex.Message));
                throw;
            }
        }
Example #16
0
        public void ShouldGetArrayOfFutureFireDateTimesForCronStringExcludingCalendarDates()
        {
            // Arrange
            const string calName = "TestCal1";
            var          cal     = new HolidayCalendar();

            cal.AddExcludedDate(new DateTime(2016, 1, 4, 12, 0, 0));

            _mockScheduler.Setup(i => i.GetCalendar(calName)).Returns(cal);

            var csu           = new CronExpressionEx("0 0 12 ? * MON-FRI *", _mockScheduler.Object);
            var dateTimeAfter = new DateTime(2016, 1, 1, 12, 0, 0);

            // Act
            var result = csu.GetFutureFireDateTimesUtcAfter(dateTimeAfter, 10, calName);

            // Assert
            Assert.Equal(10, result.Count);
            Assert.Equal(new DateTime(2016, 1, 5, 0, 0, 0), result[0].Date);
            Assert.Equal(new DateTime(2016, 1, 18, 0, 0, 0), result[9].Date);
        }
Example #17
0
        protected override void UpdateUserInterface()
        {
            CmdDelete.Enabled = DaysExcluded.SelectedIndex > -1;
            CmdAdd.Enabled    = !mExcludedDates.Contains(ExcludeDay.Value.Date);

            foreach (var excDate in mCalendar.ExcludedDates)
            {
                mCalendar.RemoveExcludedDate(excDate);
            }

            foreach (var excDate in mExcludedDates)
            {
                mCalendar.AddExcludedDate(excDate);
            }

            mCalendar.Description = string.Format("Excluding {0} dates: ", mCalendar.ExcludedDates.Count);
            foreach (var excDate in mCalendar.ExcludedDates)
            {
                mCalendar.Description += excDate.Date.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern) + ", ";
            }
            mCalendar.Description = mCalendar.Description.TrimEnd(new[] { ',', ' ' });
        }
Example #18
0
        public Task Execute(IJobExecutionContext context)
        {
            HolidayCalendar calendar = new HolidayCalendar();

            DayOfWeek toDay = DateTime.Now.DayOfWeek;

            if ((toDay == DayOfWeek.Saturday) || (toDay == DayOfWeek.Sunday))
            {
                calendar.AddExcludedDate(DateTime.Now);
                QuarztSingleton.scheduler.AddCalendar("Holiday", calendar, true, true);

                ITrigger       trigger = QuarztSingleton.scheduler.GetTrigger(new TriggerKey("NamHTtrigger", "NamHT")).GetAwaiter().GetResult();
                TriggerBuilder tb      = trigger.GetTriggerBuilder();

                ITrigger UpdateTrigger = tb.ModifiedByCalendar("Holiday").Build();

                QuarztSingleton.scheduler.RescheduleJob(new TriggerKey("NamHTtrigger", "NamHT"), UpdateTrigger);

                LogsSingleton.WriteText("Hôm nay, ngày nghỉ Job đi nhậu với bạn đây.", "Quarzt");
            }
            return(Task.FromResult("done"));
        }
Example #19
0
        public void TestTimeZone()
        {
            TimeZoneInfo    tz = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time");
            HolidayCalendar c  = new HolidayCalendar();

            c.TimeZone = tz;

            DateTimeOffset excludedDay = new DateTimeOffset(2012, 11, 4, 0, 0, 0, TimeSpan.Zero);

            c.AddExcludedDate(excludedDay.DateTime);

            // 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);
        }
Example #20
0
        public void TestHolidayCalendarDeserialization()
        {
            var calendar = Deserialize <HolidayCalendar>();

            Assert.That(calendar.ExcludedDates.Count, Is.EqualTo(1));

            calendar = Deserialize <HolidayCalendar>(23);
            Assert.That(calendar.ExcludedDates.Count, Is.EqualTo(1));

            BinaryFormatter formatter = new BinaryFormatter();

            using (var stream = new MemoryStream())
            {
                calendar = new HolidayCalendar();
                calendar.AddExcludedDate(DateTime.Now.Date);
                formatter.Serialize(stream, calendar);

                stream.Seek(0, SeekOrigin.Begin);
                stream.Position = 0;

                calendar = (HolidayCalendar)formatter.Deserialize(stream);
                Assert.That(calendar.ExcludedDates.Count, Is.EqualTo(1));
            }
        }
Example #21
0
 public void TestAddAndRemoveExclusion()
 {
     cal.AddExcludedDate(new DateTime(2007, 10, 20, 12, 40, 22));
     cal.RemoveExcludedDate(new DateTime(2007, 10, 20, 2, 0, 0));
     Assert.IsTrue(cal.ExcludedDates.Count == 0);
 }
Example #22
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var props = new NameValueCollection()
            {
                { "quartz.serializer.type", "binary" }
            };

            var factory = new StdSchedulerFactory(props);

            IScheduler sched = await factory.GetScheduler();

            await sched.Start();

            var cal = new HolidayCalendar();

            cal.AddExcludedDate(DateTime.Now.AddDays(-1));
            await sched.AddCalendar("myHolidays", cal, false, false);

            IJobDetail job = JobBuilder.Create <DumbJob>().WithIdentity("myJob", "group1")
                             .UsingJobData("jobSays", "Hello World!")
                             .UsingJobData("myFloatValue", 3.141f)
                             .Build();

            ITrigger trigger = TriggerBuilder.Create().WithIdentity("myTrigger")
                               .WithSchedule(CronScheduleBuilder.CronSchedule("0-10 * * ? * * *")) // first 10 second every minute
                               .ModifiedByCalendar("myHolidays")                                   // but not on holidays
                               .Build();

            ITrigger trigger1 = TriggerBuilder.Create().WithIdentity("trigger1", "group1")
                                .WithCronSchedule("0-10 * * ? * * *")                        // first 10 second every minute
                                .ForJob("myJob", "group1")
                                .Build();

            ITrigger trigger2 = TriggerBuilder.Create().WithIdentity("myTrigger2")
                                .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(16, 30)) // execute job daily at 16.30
                                .ModifiedByCalendar("myHolidays")                               // but not on holidays
                                .Build();

            //Build a trigger that will fire on Wednesdays at 10:42 am, in a TimeZone other than the system’s default:
            ITrigger trigger21 = TriggerBuilder.Create().WithIdentity("trigger21", "group1")
                                 .WithCronSchedule("0 42 10 ? * WED", x => x
                                                   .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time")))
                                 .Build();

            ITrigger trigger22 = TriggerBuilder.Create().WithIdentity("trigger3", "group1")
                                 .WithSchedule(CronScheduleBuilder.WeeklyOnDayAndHourAndMinute(DayOfWeek.Wednesday, 10, 42)
                                               .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time")))
                                 .Build();

            //SimpleTrigger : once at a specific moment in time, or at a specific moment in time followed by repeats at a specific interval.

            //Build a trigger for a specific moment in time, with no repeats:
            ISimpleTrigger trigger3 = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity("myTrigger3", "group1")
                                      .StartAt(DateTimeOffset.UtcNow.AddSeconds(5))
                                      .ForJob("myJob", "group1")                               // identify job with name, group strings
                                      .Build();

            //Build a trigger for a specific moment in time, then repeating every ten seconds ten times:
            ISimpleTrigger trigger4 = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity("myTrigger4", "group1")
                                      .StartAt(DateTimeOffset.UtcNow.AddSeconds(5))                               // if a start time is not given (if this line were omitted), "now" is implied
                                      .WithSimpleSchedule(x => x.WithIntervalInSeconds(10)
                                                          .WithRepeatCount(10))                                   // note that 10 repeats will give a total of 11 firings
                                      .ForJob("myJob", "group1")
                                      .Build();

            //Build a trigger that will fire once, five minutes in the future:
            ISimpleTrigger trigger5 = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity("myTrigger5", "group1")
                                      .StartAt(DateBuilder.FutureDate(5, IntervalUnit.Second))                               // use DateBuilder to create a date in the future
                                      .ForJob("myJob", "group1")
                                      .Build();

            //Build a trigger that will fire now, then repeat every five minutes, until the hour 17:10:
            ISimpleTrigger trigger6 = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity("myTrigger6", "group1")
                                      .WithSimpleSchedule(x => x.WithIntervalInSeconds(5)
                                                          .RepeatForever())
                                      .EndAt(DateBuilder.DateOf(22, 10, 0))
                                      .Build();

            //Build a trigger that will fire at the top of the next hour, then repeat every 2 hours, forever:
            ISimpleTrigger trigger7 = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity("myTrigger7") // because group is not specified, "trigger8" will be in the default group
                                      .StartAt(DateBuilder.EvenHourDate(null))                           // get the next even-hour (minutes and seconds zero ("00:00"))
                                      .WithSimpleSchedule(x => x.WithIntervalInHours(2)
                                                          .RepeatForever())
                                      // note that in this example, 'forJob(..)' is not called
                                      //  - which is valid if the trigger is passed to the scheduler along with the job
                                      .Build();

            await sched.ScheduleJob(job, trigger1);

            Console.ReadLine();
        }
Example #23
0
        private static async Task RunScheduler()
        {
            // 创建作业调度器
            ISchedulerFactory factory   = new StdSchedulerFactory();
            IScheduler        scheduler = await factory.GetScheduler();

            // 开始运行调度器
            await scheduler.Start();

            // 创建一个作业
            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("job1", "jobGroup1")
                             .StoreDurably()
                             .Build();

            // 设置trigger开始时间
            var startAt = DateTimeOffset.Now;

            // 排除一天中的时间范围不执行
            DailyCalendar dailyCalendar = new DailyCalendar(DateBuilder.DateOf(21, 0, 0).DateTime, DateBuilder.DateOf(22, 0, 0).DateTime);

            // 排除星期中的一天或多天
            WeeklyCalendar weeklyCalendar = new WeeklyCalendar();

            weeklyCalendar.SetDayExcluded(DayOfWeek.Friday, true);

            // 指定特定的日期,精确到天
            HolidayCalendar holidayCalendar = new HolidayCalendar();
            var             holidayDateTime = new DateTime(2018, 11, 11);

            holidayCalendar.AddExcludedDate(holidayDateTime);

            // 排除月份中的某天,可选值为1-31,精确到天
            MonthlyCalendar monthlyCalendar = new MonthlyCalendar();

            monthlyCalendar.SetDayExcluded(31, true);

            // 排除每年中的某天,精确到天
            AnnualCalendar annualCalendar = new AnnualCalendar();
            var            annualDateTime = new DateTime(2018, 11, 11);

            annualCalendar.SetDayExcluded(annualDateTime, true);

            // 使用表达式排除某些时间段不执行
            CronCalendar cronCalendar = new CronCalendar("* * * 24 3 ?");

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

            // trigger的附属信息
            var triggerDataMap = new JobDataMap();

            triggerDataMap.Add("name", "beck");

            // 创建触发器
            ITrigger trigger1 = TriggerBuilder.Create()
                                .WithIdentity("trigger1", "triggerGroup1")
                                .StartAt(DateBuilder.DateOf(18, 25, 40))
                                .WithDailyTimeIntervalSchedule(w => w
                                                               .WithRepeatCount(20)
                                                               .WithIntervalInSeconds(4)
                                                               .WithMisfireHandlingInstructionIgnoreMisfires())
                                //.WithSimpleSchedule(w => w
                                //                .WithRepeatCount(20)
                                //                .WithIntervalInHours(1)
                                //                .WithMisfireHandlingInstructionNowWithExistingCount())
                                .UsingJobData(triggerDataMap)
                                .WithPriority(3)
                                .Build();

            // 创建触发器
            ITrigger trigger2 = TriggerBuilder.Create()
                                .WithIdentity("trigger2", "triggerGroup1")
                                .StartAt(startAt)
                                .WithCronSchedule("* * * 24-25 3 ?")
                                .ForJob(job)
                                .UsingJobData(triggerDataMap)
                                .ModifiedByCalendar("calendar")
                                .WithPriority(7)
                                .Build();

            // 加入作业调度器中
            await scheduler.ScheduleJob(job, trigger1);

            await scheduler.ScheduleJob(trigger2);

            await Task.Delay(TimeSpan.FromMinutes(2));

            // 关闭scheduler
            await scheduler.Shutdown(true);
        }
Example #24
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
        }
Example #25
0
        static void Main(string[] args)
        {
            Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter {
                Level = Common.Logging.LogLevel.Info
            };
            try
            {
                //从工厂中获取Schedule实例
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

                //开启调度
                scheduler.Start();

                //创建1个job,并绑定到HelloJob类
                IJobDetail job = JobBuilder.Create <HelloJob>()
                                 .WithIdentity("job1", "group1")
                                 .UsingJobData("JobSays", "hello,world!")
                                 .UsingJobData("JobTimeElapsed", 10)
                                 .Build();

                //创建假日日历
                var calendar = new HolidayCalendar();
                calendar.AddExcludedDate(new DateTime(2017, 5, 14));
                scheduler.AddCalendar("myHolidays", calendar, false, true);
                //定义触发器,触发该job运行,并每隔10s运行一次
                ITrigger trigger = TriggerBuilder.Create().
                                   WithIdentity("trigger1", "group1")
                                   .StartNow()
                                   .WithSimpleSchedule(x => x.WithIntervalInSeconds(10)
                                                       .RepeatForever())
                                   .Build();

                ITrigger trigger2 = TriggerBuilder.Create()
                                    .WithIdentity("trigger2", "group1")
                                    .ForJob("job1")
                                    .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(9, 30)) //每天执行时间
                                    .ModifiedByCalendar("myHolidays")                              //但是排除假日时间
                                    .Build();

                ITrigger trigger3 = TriggerBuilder.Create()
                                    .WithIdentity("trigger3", "group1")
                                    .ForJob(job)
                                    .WithSimpleSchedule(
                    x => x.WithIntervalInSeconds(10) //每10s触发一次
                    .WithRepeatCount(10))            //共触发11次
                                    .Build();
                ISimpleTrigger trigger4 = TriggerBuilder.Create()
                                          .ForJob(job)
                                          .WithIdentity("trigger4", "group1")
                                          .StartAt(DateBuilder.FutureDate(5, IntervalUnit.Second))//未来5秒运行
                                          .Build() as ISimpleTrigger;
                //告诉quartz使用上面定义的触发器调度job
                //scheduler.ScheduleJob(job, trigger);
                //scheduler.ScheduleJob(job, trigger2);
                scheduler.ScheduleJob(job, trigger3);
                //睡眠1min 展示发生的事情
                Thread.Sleep(TimeSpan.FromSeconds(600));

                //当程序结束时 关闭调度任务
                scheduler.Shutdown();
            }
            catch (SchedulerException ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("Press any key to close the application");
            Console.ReadKey();
        }
Example #26
0
        public void StartScheduler()
        {
            StdSchedulerFactory factory   = new StdSchedulerFactory();
            IScheduler          scheduler = factory.GetScheduler();

            string    myJobName   = "MyFirstJob";
            string    myGroupName = "MyGroup";
            JobKeySet jobNames    = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(myGroupName));

            if (!scheduler.CheckExists(JobKey.Create(myJobName, myGroupName)))
            {
                IJobDetail job = JobBuilder.Create <ConsoleJob1>()
                                 .WithIdentity(myJobName, myGroupName)
                                 .UsingJobData("ExtraText", "Plinko")
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("myFirstTrigger", myGroupName)
                                   .StartNow()
                                   .WithSimpleSchedule(x => x
                                                       .WithIntervalInMinutes(2)
                                                       .RepeatForever())
                                   .Build();

                scheduler.ScheduleJob(job, trigger);
            }

            if (!jobNames.Any(k => k.Name == "HelloWorld1"))
            {
                IJobDetail job = JobBuilder.Create <NoOpJob>()
                                 .WithIdentity("HelloWorld1", myGroupName)
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("HelloWorld1Trigger", myGroupName)
                                   .StartNow()
                                   .WithSimpleSchedule(x => x
                                                       .WithIntervalInMinutes(15)
                                                       .RepeatForever())
                                   .Build();

                scheduler.ScheduleJob(job, trigger);
            }

            if (!scheduler.CheckExists(JobKey.Create("HelloWorld2", myGroupName)))
            {
                HolidayCalendar calendar = new HolidayCalendar();
                calendar.AddExcludedDate(DateTime.Now.ToUniversalTime());
                calendar.AddExcludedDate(DateTime.Now.AddDays(4).ToUniversalTime());
                scheduler.AddCalendar("randomHolidays", calendar, true, true);

                IJobDetail job = JobBuilder.Create <NoOpJob>()
                                 .WithIdentity("HelloWorld2", myGroupName)
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("HelloWorld2Trigger", myGroupName)
                                   .StartNow()
                                   .WithDailyTimeIntervalSchedule(x => x
                                                                  .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(15, 0)))
                                   .ModifiedByCalendar("randomHolidays")
                                   .Build();

                scheduler.ScheduleJob(job, trigger);
            }

            if (!scheduler.CheckExists(JobKey.Create("TimeTrackerReminder", myGroupName)))
            {
                IJobDetail job = JobBuilder.Create <NoOpJob>()
                                 .WithIdentity("TimeTrackerReminder", myGroupName)
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("EveryMondayAtEight", myGroupName)
                                   .StartNow()
                                   .WithDailyTimeIntervalSchedule(x => x
                                                                  .OnDaysOfTheWeek(DayOfWeek.Monday)
                                                                  .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(8, 0)))
                                   .Build();

                scheduler.ScheduleJob(job, trigger);
            }

            //if (!scheduler.CheckExists(JobKey.Create("UnscheduledJob", myGroupName)))
            //{
            //	IJobDetail job = JobBuilder.Create<NoOpJob>()
            //		.WithIdentity("UnscheduledJob", myGroupName)
            //		.Build();

            //	scheduler.AddJob(job, true);
            //}

            if (!scheduler.CheckExists(JobKey.Create("TwoAliens", myGroupName)))
            {
                IJobDetail job = JobBuilder.Create <TwoAlienJob>()
                                 .WithIdentity("TwoAliens", myGroupName)
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("EveryFullMoon", myGroupName)
                                   .StartNow()
                                   .WithCronSchedule("0 59 23 28 1/1 ? *")
                                   .Build();

                scheduler.ScheduleJob(job, trigger);
            }


            scheduler.Start();
        }