コード例 #1
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);
        }
コード例 #2
0
        void ConfigureQuartz(IServiceCollection services)
        {
            var properties = new System.Collections.Specialized.NameValueCollection
            {
                ["quartz.serializer.type"]        = "binary",
                ["quartz.scheduler.instanceName"] = "XmlConfiguredInstance",
                ["quartz.threadPool.type"]        = "Quartz.Simpl.SimpleThreadPool, Quartz",
                ["quartz.threadPool.threadCount"] = "10",
                ["quartz.plugin.xml.type"]        = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins",
                ["quartz.plugin.xml.fileNames"]   = "~/quartz_jobs.config",
                // this is the default
                ["quartz.plugin.xml.FailOnFileNotFound"] = "true",
                // this is not the default
                ["quartz.plugin.xml.failOnSchedulingError"] = "true"
            };

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

            //var liveLogPlugin = new LiveLogPlugin();
            //scheduler.ListenerManager.AddJobListener(liveLogPlugin);
            //scheduler.ListenerManager.AddTriggerListener(liveLogPlugin);
            //scheduler.ListenerManager.AddSchedulerListener(liveLogPlugin);

            scheduler.AddCalendar(typeof(AnnualCalendar).Name, new AnnualCalendar(), false, false);
            scheduler.AddCalendar(typeof(CronCalendar).Name, new CronCalendar("0 0/5 * * * ?"), false, false);
            scheduler.AddCalendar(typeof(DailyCalendar).Name, new DailyCalendar("12:01", "13:04"), false, false);
            scheduler.AddCalendar(typeof(HolidayCalendar).Name, new HolidayCalendar(), false, false);
            scheduler.AddCalendar(typeof(MonthlyCalendar).Name, new MonthlyCalendar(), false, false);
            //scheduler.AddCalendar(typeof (WeeklyCalendar).Name, new WeeklyCalendar(), false, false);

            services.AddSingleton(scheduler);
        }
コード例 #3
0
        private IServiceProvider ConfigureQuartz(IServiceCollection services)
        {
            // First we must get a reference to a scheduler
            ISchedulerFactory sf        = new StdSchedulerFactory();
            IScheduler        scheduler = sf.GetScheduler().Result;

            var sp1 = services.BuildServiceProvider();

            scheduler.JobFactory = new DiJobFactory(sp1);

            // var liveLogPlugin = new LiveLogPlugin();
            // scheduler.ListenerManager.AddJobListener(liveLogPlugin);
            // scheduler.ListenerManager.AddTriggerListener(liveLogPlugin);
            // scheduler.ListenerManager.AddSchedulerListener(liveLogPlugin);

            scheduler.AddCalendar(typeof(AnnualCalendar).Name, new AnnualCalendar(), false, false);
            scheduler.AddCalendar(typeof(CronCalendar).Name, new CronCalendar("0 0/5 * * * ?"), false, false);
            scheduler.AddCalendar(typeof(DailyCalendar).Name, new DailyCalendar("12:01", "13:04"), false, false);
            scheduler.AddCalendar(typeof(HolidayCalendar).Name, new HolidayCalendar(), false, false);
            scheduler.AddCalendar(typeof(MonthlyCalendar).Name, new MonthlyCalendar(), false, false);
            //scheduler.AddCalendar(typeof (WeeklyCalendar).Name, new WeeklyCalendar(), false, false);

            services.AddSingleton <IScheduler>(scheduler);
            scheduler.Start();

            return(sp1);
        }
コード例 #4
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);
        }
コード例 #5
0
        public void StartSample()
        {
            ICalendar cal = new UserDefinedCalendar();

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

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

            sched.Start();
            sched.AddCalendar("userDefinedCalendar", cal, false, true);

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

            // Trigger the job to run now, and then every 5 seconds
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("myTrigger", "group1")
                               .StartNow()
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInSeconds(1)
                                                   .RepeatForever())
                               .ModifiedByCalendar("userDefinedCalendar") // but not on "user defined" calendar
                               .Build();

            sched.ScheduleJob(job, trigger);
        }
コード例 #6
0
        private async Task InitializeScheduler(IScheduler scheduler, CancellationToken cancellationToken)
        {
            foreach (var listener in serviceProvider.GetServices <ISchedulerListener>())
            {
                scheduler.ListenerManager.AddSchedulerListener(listener);
            }

            var jobListeners = serviceProvider.GetServices <IJobListener>();

            foreach (var configuration in serviceProvider.GetServices <JobListenerConfiguration>())
            {
                var listener = jobListeners.First(x => x.GetType() == configuration.ListenerType);
                scheduler.ListenerManager.AddJobListener(listener, configuration.Matchers);
            }

            var triggerListeners = serviceProvider.GetServices <ITriggerListener>();

            foreach (var configuration in serviceProvider.GetServices <TriggerListenerConfiguration>())
            {
                var listener = triggerListeners.First(x => x.GetType() == configuration.ListenerType);
                scheduler.ListenerManager.AddTriggerListener(listener, configuration.Matchers);
            }

            var calendars = serviceProvider.GetServices <CalendarConfiguration>();

            foreach (var configuration in calendars)
            {
                await scheduler.AddCalendar(configuration.Name, configuration.Calendar, configuration.Replace, configuration.UpdateTriggers, cancellationToken);
            }

            await processor.ScheduleJobs(scheduler, cancellationToken);
        }
コード例 #7
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);
        }
コード例 #8
0
        public static async Task <string> Run()
        {
            var properties = new NameValueCollection
            {
                ["quartz.scheduler.instanceName"] = "XmlConfiguredInstance",
                ["quartz.threadPool.type"]        = "Quartz.Simpl.SimpleThreadPool, Quartz",
                ["quartz.threadPool.threadCount"] = "5",
                ["quartz.plugin.xml.type"]        = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz",
                ["quartz.plugin.xml.fileNames"]   = "~/quartz_jobs.xml",
                ["quartz.serializer.type"]        = "json"
            };

            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = await sf.GetScheduler();

            var dailyCalendar = new DailyCalendar("00:01", "23:59");

            dailyCalendar.InvertTimeRange = true;
            await sched.AddCalendar("cal1", dailyCalendar, false, false);

            await sched.Start();

            WebApi.Program.Main(null);

            return("OK");
        }
コード例 #9
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);
        }
コード例 #10
0
ファイル: CalendarBuilder.cs プロジェクト: aries544/eXpand
 public static void Build(IXpandJobTrigger trigger, IScheduler scheduler) {
     if (trigger.Calendar != null) {
         var calendar = (ICalendar)XafTypesInfo.Instance.FindTypeInfo(trigger.Calendar.CalendarTypeFullName).Type.CreateInstance();
         Initialize(calendar, trigger);
         scheduler.AddCalendar(trigger.Calendar.Name, calendar, true, true);
     }
 }
コード例 #11
0
        public void StartScheduler_WithJobsAndTriggers_DeletedSuccessfully()
        {
            //arrange
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = sf.GetScheduler().Result;
            var job      = CreateJob();
            var trigger  = CreateTrigger("testTrigger1", "triggerGroup", job.Key, "0/5 * * * * ?");
            var calendar = CreateCalendar();

            sched.AddCalendar("testCalendar", calendar, false, false);
            sched.ScheduleJob(job, trigger);
            sched.Start();

            //act
            sched.DeleteJob(job.Key);
            sched.Shutdown();

            //assert
            IJobDetail jobDetail = JobStore.RetrieveJob(job.Key).Result;

            Assert.IsNull(jobDetail);

            var _trigger = JobStore.RetrieveTrigger(trigger.Key).Result;

            Assert.IsNull(_trigger);
        }
コード例 #12
0
 /// <summary>
 /// 添加Calendar
 /// </summary>
 /// <returns></returns>
 public JsonResult AddCalendar(DSRWControlViewModel_AddCalendar model)
 {
     if (model.calendarType == "DailyCalendar")
     {
         var list_startTime = model.startTime.Split(':');
         var list_endTime   = model.endTime.Split(':');
         if (list_startTime.Length > 1 && list_endTime.Length > 1)
         {
             var cale = new DailyCalendar(
                 string.Format("{0}:{1}:{2}", list_startTime.ElementAt(0),
                               list_startTime.ElementAt(1),
                               list_startTime.ElementAt(2)),
                 string.Format("{0}:{1}:{2}", list_endTime.ElementAt(0),
                               list_endTime.ElementAt(1),
                               list_endTime.ElementAt(2))
                 );
             cale.Description = model.description;
             scheduler.AddCalendar(model.calendarName, cale, true, true);
             var trigger = scheduler.GetTrigger(new TriggerKey(model.triggerName, model.triggerGroup));
             if (trigger != null)
             {
                 //如果触发器存在则,修改触发器,调用修改Calendar方法
                 var newTrigger = trigger.GetTriggerBuilder().ModifiedByCalendar(model.calendarName).Build();
                 //更新Schedule
                 scheduler.RescheduleJob(new TriggerKey(model.triggerName, model.triggerGroup), newTrigger);
             }
             return(Json(new {
                 code = "1",
                 msg = ""
             }));
         }
         else
         {
             return(Json(new {
                 code = "999999",
                 msg = "请输入起始时间和结束时间"
             }));
         }
     }
     else
     {
         return(Json(new {
             code = "101",
             msg = "目前只支持DaliyCalendar模式"
         }));
     }
 }
コード例 #13
0
        public void Run()
        {
            ILog log = LogManager.GetLogger(typeof(XmlConfigurationExample));

            log.Info("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"] = "XmlConfiguredInstance";

            // set thread pool info
            properties["quartz.threadPool.type"]           = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]    = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // job initialization plugin handles our xml reading, without it defaults are used
            properties["quartz.plugin.xml.type"]      = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz";
            properties["quartz.plugin.xml.fileNames"] = "~/quartz_jobs.xml";


            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = sf.GetScheduler();

            // we need to add calendars manually, lets create a silly sample calendar
            var dailyCalendar = new DailyCalendar("00:01", "23:59");

            dailyCalendar.InvertTimeRange = true;
            sched.AddCalendar("cal1", dailyCalendar, false, false);

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

            // all jobs and triggers are now in scheduler


            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            sched.Start();
            log.Info("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to
            // fire the triggers
            log.Info("------- Waiting 30 seconds... -------------");

            try
            {
                Thread.Sleep(30 * 1000);
            }
            catch (ThreadInterruptedException)
            {
            }

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");
        }
コード例 #14
0
 public static void Build(IXpandJobTrigger trigger, IScheduler scheduler)
 {
     if (trigger.Calendar != null)
     {
         var calendar = (ICalendar)Activator.CreateInstance(XafTypesInfo.Instance.FindTypeInfo(trigger.Calendar.CalendarTypeFullName).Type);
         Initialize(calendar, trigger);
         scheduler.AddCalendar(trigger.Calendar.Name, calendar, true, true);
     }
 }
コード例 #15
0
        public static async Task Configure(this IScheduler scheduler, SchedulerConfigurator schedulerConfigurator)
        {
            if (schedulerConfigurator == null)
            {
                return;
            }

            var log = HostLogger.Get(typeof(SchedulerConfigurator));

            if (schedulerConfigurator.JobListeners != null && schedulerConfigurator.JobListeners.Any())
            {
                foreach (var listener in schedulerConfigurator.JobListeners)
                {
                    var config = listener();
                    scheduler.ListenerManager.AddJobListener(config.Listener, config.Matchers);
                    log.Info($"[Topshelf.Quartz] Added Job Listener: {config.Listener.Name}");
                }
            }

            if (schedulerConfigurator.TriggerListeners != null && schedulerConfigurator.TriggerListeners.Any())
            {
                foreach (var listener in schedulerConfigurator.TriggerListeners)
                {
                    var config = listener();
                    scheduler.ListenerManager.AddTriggerListener(config.Listener, config.Matchers);
                    log.Info($"[Topshelf.Quartz] Added Trigger Listener: {config.Listener.Name}");
                }
            }

            if (schedulerConfigurator.ScheduleListeners != null && schedulerConfigurator.ScheduleListeners.Any())
            {
                foreach (var listener in schedulerConfigurator.ScheduleListeners)
                {
                    var scheduleListener = listener();
                    scheduler.ListenerManager.AddSchedulerListener(scheduleListener);
                    log.Info($"[Topshelf.Quartz] Added Schedule Listener: {scheduleListener.GetType()}");
                }
            }

            if (schedulerConfigurator.Calendars != null && schedulerConfigurator.Calendars.Any())
            {
                foreach (var calendar in schedulerConfigurator.Calendars)
                {
                    var cal = calendar();

                    if (cal.CalName.IsNullOrWhiteSpace() || cal.Calendar == null)
                    {
                        continue;
                    }

                    await scheduler.AddCalendar(cal.CalName, cal.Calendar, true, true);

                    log.Info($"[Topshelf.Quartz] Added Calendar: {cal.CalName}");
                }
            }
        }
コード例 #16
0
ファイル: TypeLoader.cs プロジェクト: dominikjeske/HomeCenter
        private async Task LoadCalendars()
        {
            foreach (var calendarType in AssemblyHelper.GetAllTypes <IDayOffProvider>())
            {
                var dayOffProvider = calendarType.CreateInstance <IDayOffProvider>();
                var calendar       = new QuartzCalendar(dayOffProvider);

                await _scheduler.AddCalendar(dayOffProvider.Name, calendar, false, false);
            }
        }
コード例 #17
0
        public async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(XmlConfigurationExample));

            log.Info("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            var properties = new NameValueCollection
            {
                ["quartz.scheduler.instanceName"] = "XmlConfiguredInstance",
                ["quartz.threadPool.type"]        = "Quartz.Simpl.SimpleThreadPool, Quartz",
                ["quartz.threadPool.threadCount"] = "5",
                ["quartz.plugin.xml.type"]        = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins",
                ["quartz.plugin.xml.fileNames"]   = "~/quartz_jobs.xml",
                // this is the default
                ["quartz.plugin.xml.FailOnFileNotFound"] = "true",
                // this is not the default
                ["quartz.plugin.xml.failOnSchedulingError"] = "true"
            };

            // set thread pool info

            // job initialization plugin handles our xml reading, without it defaults are used

            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = await sf.GetScheduler();

            // we need to add calendars manually, lets create a silly sample calendar
            var dailyCalendar = new DailyCalendar("00:01", "23:59");

            dailyCalendar.InvertTimeRange = true;
            await sched.AddCalendar("cal1", dailyCalendar, false, false);

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

            // all jobs and triggers are now in scheduler

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

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

            // wait long enough so that the scheduler as an opportunity to
            // fire the triggers
            log.Info("------- Waiting 30 seconds... -------------");

            await Task.Delay(30 *1000);

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

            log.Info("------- Shutdown Complete -----------------");
        }
コード例 #18
0
        public JsonResult AddCalendar(CalendarRequestEntity calendarReq)
        {
            try
            {
                var calendar = scheduler.GetCalendar(calendarReq.calendarname);

                //获取calendar
                if (calendar != null)
                {
                    return(Json("已经有同名的calendar添加,请勿添加"));
                }

                if (calendarReq.calendartype == "DailyCalendar")
                {
                    var segment   = calendarReq.selectdate.Split(',');
                    var starttime = DateBuilder.DateOf(Convert.ToInt32(segment[0]), 0, 0).DateTime;
                    var endtime   = DateBuilder.DateOf(Convert.ToInt32(segment[1]), 0, 0).DateTime;

                    DailyCalendar dailyCalendar = new DailyCalendar(starttime, endtime);

                    scheduler.AddCalendar(calendarReq.calendarname, dailyCalendar, true, true);

                    //将这个calendar设置给trigger
                    var tkeys = calendarReq.triggerkey.Split('.');

                    var trigger = scheduler.GetTrigger(new TriggerKey(tkeys[1], tkeys[0]));

                    if (trigger != null)
                    {
                        var newTrigger = trigger.GetTriggerBuilder().ModifiedByCalendar(calendarReq.calendarname).Build();

                        scheduler.RescheduleJob(trigger.Key, newTrigger);
                    }
                }

                return(Json(1));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #19
0
        public async Task AddCalendar(HolidayCalendar holidayCalendar)
        {
            var holidayDates = holidayCalendar.Config.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(r => DateTime.Parse(r));

            Quartz.Impl.Calendar.HolidayCalendar calendar = new Quartz.Impl.Calendar.HolidayCalendar();
            foreach (var holidayDate in holidayDates)
            {
                calendar.AddExcludedDate(holidayDate);
            }
            await _scheduler.AddCalendar($"{holidayCalendar.Id}_calendar", calendar, false, false);
        }
コード例 #20
0
        private void AddCalendar(CalendarsNode calNode, Action updateAction)
        {
            var allCals = mScheduler.GetCalendarNames();
            var frm     = new AddCalendar(allCals);

            if (frm.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            mScheduler.AddCalendar(frm.Calendar.Description, frm.Calendar, true, true);
            updateAction();
        }
コード例 #21
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);
        }
コード例 #22
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}个作业");
        }
コード例 #23
0
        /// <summary>
        /// Registers the calendars to the scheduler.
        /// </summary>
        /// <param name="sched">The sched.</param>
        private void RegisterCalendars(IScheduler sched)
        {
            foreach (var g in RegisterGroups)
            {
                ICalendar cal = g.Calendar;

                if (cal != null)
                {
                    string newCalendarName = string.Format("CAL_{0}", Guid.NewGuid());
                    sched.AddCalendar(newCalendarName, cal, true, true);

                    g.TriggerBuilder.ModifiedByCalendar(newCalendarName);
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Registers the calendars to the scheduler.
        /// </summary>
        /// <param name="sched">The sched.</param>
        private void RegisterCalendars(IScheduler sched)
        {
            foreach (var g in RegisterGroups)
            {
                ICalendar cal = g.Calendar;

                if (cal != null)
                {
                    string newCalendarName = string.Format("CAL_{0}", Guid.NewGuid());
                    sched.AddCalendar(newCalendarName, cal, true, true);

                    g.TriggerBuilder.ModifiedByCalendar(newCalendarName);
                }
            }
        }
コード例 #25
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);
        }
コード例 #26
0
ファイル: Service1.cs プロジェクト: tayduivn/SocialPayments
        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;
            }
        }
コード例 #27
0
        public void Initialize(string pluginName, IScheduler scheduler)
        {
            var liveLogPlugin = new LiveLogPlugin();
            scheduler.ListenerManager.AddJobListener(liveLogPlugin);
            scheduler.ListenerManager.AddTriggerListener(liveLogPlugin);
            scheduler.ListenerManager.AddSchedulerListener(liveLogPlugin);

            // TODO REMOVE
            scheduler.AddCalendar(typeof (AnnualCalendar).Name, new AnnualCalendar(), false, false);
            scheduler.AddCalendar(typeof (CronCalendar).Name, new CronCalendar("0 0/5 * * * ?"), false, false);
            scheduler.AddCalendar(typeof (DailyCalendar).Name, new DailyCalendar("12:01", "13:04"), false, false);
            scheduler.AddCalendar(typeof (HolidayCalendar).Name, new HolidayCalendar(), false, false);
            scheduler.AddCalendar(typeof (MonthlyCalendar).Name, new MonthlyCalendar(), false, false);
            scheduler.AddCalendar(typeof (WeeklyCalendar).Name, new WeeklyCalendar(), false, false);
        }
コード例 #28
0
        public Conductor(List <JobDefinition> jobDefinitions, List <ICalendar> calendars, double intervalToCheckForLongRunningJobsInMs, double intervalToCheckForJobsToTerminateInMs,
                         IScheduler scheduler, IProcessManager processManager)
        {
            _scheduler = scheduler;

            _warningTimer           = new Timer(intervalToCheckForLongRunningJobsInMs);
            _warningTimer.Elapsed  += WarningTimerElapsed;
            _warningTimer.AutoReset = true;

            _terminationTimer           = new Timer(intervalToCheckForJobsToTerminateInMs);
            _terminationTimer.Elapsed  += TerminationTimerElapsed;
            _terminationTimer.AutoReset = true;

            _processManager = processManager;

            calendars.ForEach(c => _scheduler.AddCalendar(c.Description, c, true, true));

            AddJobsToScheduler(jobDefinitions);

            _logger = LogManager.GetLogger(GetType());
        }
コード例 #29
0
        public void Initialize(string pluginName, IScheduler scheduler)
        {
            var liveLogPlugin = new LiveLogPlugin();

            scheduler.ListenerManager.AddJobListener(liveLogPlugin);
            scheduler.ListenerManager.AddTriggerListener(liveLogPlugin);
            scheduler.ListenerManager.AddSchedulerListener(liveLogPlugin);

            // TODO REMOVE
            scheduler.AddCalendar(typeof(AnnualCalendar).Name, new AnnualCalendar(), false, false);
            scheduler.AddCalendar(typeof(CronCalendar).Name, new CronCalendar("0 0/5 * * * ?"), false, false);
            scheduler.AddCalendar(typeof(DailyCalendar).Name, new DailyCalendar("12:01", "13:04"), false, false);
            scheduler.AddCalendar(typeof(HolidayCalendar).Name, new HolidayCalendar(), false, false);
            scheduler.AddCalendar(typeof(MonthlyCalendar).Name, new MonthlyCalendar(), false, false);
            scheduler.AddCalendar(typeof(WeeklyCalendar).Name, new WeeklyCalendar(), false, false);
        }
コード例 #30
0
        public Task Initialize(string pluginName, IScheduler scheduler, CancellationToken cancellationToken)
        {
            // var liveLogPlugin = new LiveLogPlugin();
            // scheduler.ListenerManager.AddJobListener(liveLogPlugin);
            // scheduler.ListenerManager.AddTriggerListener(liveLogPlugin);
            // scheduler.ListenerManager.AddSchedulerListener(liveLogPlugin);

            // TODO REMOVE
            scheduler.AddCalendar(typeof(AnnualCalendar).Name, new AnnualCalendar(), false, false, cancellationToken);
            scheduler.AddCalendar(typeof(CronCalendar).Name, new CronCalendar("0 0/5 * * * ?"), false, false, cancellationToken);
            scheduler.AddCalendar(typeof(DailyCalendar).Name, new DailyCalendar("12:01", "13:04"), false, false, cancellationToken);
            scheduler.AddCalendar(typeof(HolidayCalendar).Name, new HolidayCalendar(), false, false, cancellationToken);
            scheduler.AddCalendar(typeof(MonthlyCalendar).Name, new MonthlyCalendar(), false, false, cancellationToken);
            scheduler.AddCalendar(typeof(WeeklyCalendar).Name, new WeeklyCalendar(), false, false, cancellationToken);

            return(Task.CompletedTask);
        }
コード例 #31
0
ファイル: SmokeTestPerformer.cs プロジェクト: zidad/quartznet
        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);
            }
        }
コード例 #32
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();
        }
コード例 #33
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.");
        }
コード例 #34
0
		/// <summary>
		/// Adds a calendar.
		/// </summary>
		/// <param name="sched">The sched.</param>
		/// <param name="calendarBundle">calendar bundle.</param>
		/// <throws>  SchedulerException if the Calendar cannot be added to the Scheduler, or </throws>
		public virtual void AddCalendar(IScheduler sched, CalendarBundle calendarBundle)
		{
			sched.AddCalendar(calendarBundle.CalendarName, calendarBundle.Calendar, calendarBundle.Replace, true);
		}
コード例 #35
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);
                   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);

                   scheduler.ScheduleJob(job, nt);

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

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

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

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

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

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

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

                   scheduler.ScheduleJob(intervalTrigger);

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