コード例 #1
0
ファイル: MainForm.cs プロジェクト: aiime/nochnik
        void StopNochnikEveryDay()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;

            scheduler.Start();

            IJobDetail job = JobBuilder.Create <StopNochnikJob>()
                             .WithIdentity("StopNochnik")
                             .Build();

            job.JobDataMap["wallpaperClock"] = wallpaperClock;
            job.JobDataMap["userController"] = userController;

            XmlDocument timeInfo = new XmlDocument();

            timeInfo.Load(AppDomain.CurrentDomain.BaseDirectory + @"\time_info.xml");
            int shiftEndHour   = Int32.Parse(timeInfo.GetElementsByTagName("shift_end_hour")[0].InnerText);
            int shiftEndMinute = Int32.Parse(timeInfo.GetElementsByTagName("shift_end_minute")[0].InnerText);
            int shiftEndSecond = Int32.Parse(timeInfo.GetElementsByTagName("shift_end_second")[0].InnerText);

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("StopNochnikTrigger")
                               .StartAt(DateBuilder.TodayAt(shiftEndHour, shiftEndMinute, shiftEndSecond))
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInHours(24)
                                                   .RepeatForever())
                               .Build();

            scheduler.ScheduleJob(job, trigger);
        }
コード例 #2
0
ファイル: SchedulerUtils.cs プロジェクト: dotiendai1996/asd
        public void StartAsync()
        {
            var configs = AppConfigSection.GetInstance();

            if (configs.Scheduler.Enable)
            {
                TimeSpan time;
                if (TimeSpan.TryParse(configs.Scheduler.TimeStartJob, out time))
                {
                    // construct a scheduler factory
                    ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

                    // get a scheduler, start the schedular before triggers or anything else
                    scheduler = schedulerFactory.GetScheduler();
                    scheduler.Start();

                    IJobDetail job = JobBuilder.Create <DeviceJob>()
                                     .WithIdentity("DeviceJob", "DeviceChamCong")
                                     .Build();

                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity("DeviceTrigger", "DeviceChamCong")
                                       .StartAt(DateBuilder.TodayAt(time.Hours, time.Minutes, time.Seconds))
                                       .WithSimpleSchedule(schedule =>
                    {
                        schedule.RepeatForever()
                        .WithIntervalInHours(configs.Scheduler.HoursRepeat);
                    })
                                       .Build();

                    scheduler.ScheduleJob(job, trigger);
                }
            }
        }
コード例 #3
0
        public async Task TestScheduleInMiddleOfDailyInterval()
        {
            DateTimeOffset currTime = DateTimeOffset.UtcNow;

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

            NameValueCollection properties = new NameValueCollection();

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

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

            await scheduler.ScheduleJob(job, trigger);

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

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

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

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

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

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

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

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

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

            await scheduler.Shutdown();
        }
コード例 #4
0
        /// <summary>
        /// Schedules configured backups, and a daily cleanup task.
        /// </summary>
        public void ScheduleJobs()
        {
            LogHandler          logHandler = new LogHandler();
            List <DatabaseInfo> dbNodes    = new DatabasesXmlHandler().GetAllDatabaseNodes();

            if (0 == dbNodes.Count)
            {
                logHandler.LogMessage(LogHandler.MessageType.WARNING, "MySQL Backup Scheduler - No database nodes found. No backups will be scheduled.");
            }
            else
            {
                try
                {
                    scheduler = StdSchedulerFactory.GetDefaultScheduler();
                    scheduler.Start();
                    foreach (DatabaseInfo dbNode in dbNodes)
                    {
                        //Schedule backup job
                        IJobDetail backupJobDetail = JobBuilder.Create <CreateBackupJob>()
                                                     .WithIdentity(dbNode.ID.ToString() + "_Job", "Backup")
                                                     .UsingJobData(CreateBackupJob.Properties.DatabaseId.ToString(), dbNode.ID.ToString())
                                                     .Build();
                        ITrigger backupJobTrigger = TriggerBuilder.Create()
                                                    .WithIdentity(dbNode.ID.ToString() + "_Trigger", "Backup")
                                                    .StartAt(DateBuilder.TodayAt(dbNode.StartTime.Hours, dbNode.StartTime.Minutes, 0))
                                                    .WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
                                                    .Build();
                        scheduler.ScheduleJob(backupJobDetail, backupJobTrigger);
                        logHandler.LogMessage(LogHandler.MessageType.INFO, "Backup job scheduled for database: " + dbNode.DatabaseName + " @ " + dbNode.Host);
                    }
                    //Schedule cleanup job
                    IJobDetail cleanupJobDetail = JobBuilder.Create <DeleteOldBackupsJob>()
                                                  .WithIdentity("Delete_Old_Job", "Cleanup")
                                                  .Build();
                    ITrigger cleanupTrigger = TriggerBuilder.Create()
                                              .WithIdentity("Delete_Old_Trigger", "Cleanup")
                                              .StartAt(DateBuilder.TodayAt(1, 0, 0))
                                              .WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
                                              .Build();
                    scheduler.ScheduleJob(cleanupJobDetail, cleanupTrigger);
                    logHandler.LogMessage(LogHandler.MessageType.INFO, "Cleanup job scheduled.");
                }
                catch (Exception ex)
                {
                    logHandler.LogMessage(LogHandler.MessageType.ERROR, "Error scheduling backup jobs: " + ex.ToString());
                }
            }
        }
コード例 #5
0
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

            scheduler.Start();

            IJobDetail googleChecker    = JobBuilder.Create <SiteStatusChecker>().Build();
            IJobDetail appleChecker     = JobBuilder.Create <SiteStatusChecker>().Build();
            IJobDetail microsoftChecker = JobBuilder.Create <SiteStatusChecker>().Build();

            googleChecker.JobDataMap["url"]    = "https://www.google.com"; //for sending in Execute() method in job class
            appleChecker.JobDataMap["url"]     = "https://www.apple.com";
            microsoftChecker.JobDataMap["url"] = "https://www.Microsoft.com";

            ITrigger triggerGoogle = TriggerBuilder.Create()    // create trigger
                                     .WithIdentity("triggerGoogle", "checkerGroup")
                                     .StartNow()                //start now
                                     .WithSimpleSchedule(x => x // setting shedule
                                                         .WithIntervalInMinutes(2)
                                                         .RepeatForever())
                                     .Build();

            scheduler.ScheduleJob(googleChecker, triggerGoogle);        // begin executing work

            ITrigger triggerApple = TriggerBuilder.Create()
                                    .WithIdentity("triggerApple", "checkerGroup")
                                    .WithSimpleSchedule(x => x
                                                        .WithIntervalInMinutes(5)
                                                        .RepeatForever())
                                    .Build();

            scheduler.ScheduleJob(appleChecker, triggerApple);

            ITrigger triggerMicrosoft = TriggerBuilder.Create()
                                        .WithIdentity("triggerMicrosoft", "checkerGroup")
                                        .StartAt(DateBuilder.TodayAt(22, 15, 00)) //set specific time for start
                                        .WithSimpleSchedule(x => x
                                                            .WithIntervalInHours(48)
                                                            .RepeatForever())
                                        .Build();

            scheduler.ScheduleJob(microsoftChecker, triggerMicrosoft);
        }
コード例 #6
0
        public void Schedule(MagicBoxOrder magicBox)
        {
            var nexttime = magicBox.ExecutingTime;

            var jobDetail = JobBuilder.Create <MagicBoxOrderJob>()
                            .WithIdentity(magicBox.Id, "group1")
                            .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(magicBox.Id, "group1")
                          .StartAt(DateBuilder.TodayAt(nexttime.Hour, nexttime.Minute, nexttime.Second))
                          .Build();

            // should group this together in one command. just execute when arrived there

            jobDetail.JobDataMap.Add("queue", orderQueue);
            jobDetail.JobDataMap.Add("orders", magicBox);

            scheduler.ScheduleJob(jobDetail, trigger);
        }
コード例 #7
0
        protected override void OnStart(string[] args)
        {
            LogHelper.Log.Info("正在启动....");
            if (RepositoryService.TestWriteConnection())
            {
                LogHelper.Log.Info("写数据库连接正常");
            }
            else
            {
                LogHelper.Log.Info("写数据库连接异常");
                return;
            }
            if (RepositoryService.TestReadConnection())
            {
                LogHelper.Log.Info("读数据库连接正常");
            }
            else
            {
                LogHelper.Log.Info("读数据库连接异常");
                return;
            }
            LogHelper.Log.Info("服务已启动");

            DateTimeOffset runTime = DateBuilder.TodayAt(01, 00, 00);
            ITrigger       trigger = TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(runTime).WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever(24))
                                     .Build();

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

            ISchedulerFactory sf = new StdSchedulerFactory();

            sched = sf.GetScheduler();
            sched.ScheduleJob(detail, trigger);

            sched.Start();

            LogHelper.Log.Info("调度任务已启动");
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: otot333/QuartznetLab
        private static async Task InitializationScheduler()
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            var job1 = JobBuilder.Create <HelloJob>()
                       .WithIdentity("Job1")
                       .StoreDurably(true).Build();

            var dinnerTime = DateBuilder.TodayAt(14, 33, 50);
            var trigger    = TriggerBuilder.Create()
                             .StartNow()
                             .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
                             .ForJob("Job1").Build();
            await scheduler.AddJob(job1, true);

            await scheduler.ScheduleJob(trigger);

            scheduler.ListenerManager.AddJobListener(
                new MyJobListener(),
                KeyMatcher <JobKey> .KeyEquals(new JobKey("Job1")));
            await scheduler.Start();
        }
コード例 #9
0
ファイル: Startup.cs プロジェクト: sandrohanea/BeatTheGame
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddBlazorFluentUI();
            services.AddTransient <IPlayerService, PlayerService>();
            services.AddTransient <IDeckService, DeckService>();
            services.AddTransient <INotificationService, NotificationService>();
            services.AddTransient <IGameSessionService, GameSessionService>();
            services.AddTransient <CleanOldGamesJob>();

            services.AddQuartz(q =>
            {
                q.SchedulerId = "Scheduler-Core";
                q.UseMicrosoftDependencyInjectionJobFactory(options =>
                {
                    options.AllowDefaultConstructor = true;
                });
                q.UseSimpleTypeLoader();
                q.UseInMemoryStore();
                q.UseDefaultThreadPool(tp =>
                {
                    tp.MaxConcurrency = 10;
                });
                q.ScheduleJob <CleanOldGamesJob>(trigger => trigger
                                                 .WithIdentity("Clean Games Job")
                                                 .StartAt(DateBuilder.TodayAt(23, 59, 59))
                                                 .WithDailyTimeIntervalSchedule(x => x.WithInterval(24, IntervalUnit.Hour))
                                                 .WithDescription("The Trigger for daily game sessions cleaning.")
                                                 );
            });

            services.AddQuartzServer(options =>
            {
                // when shutting down we want jobs to complete gracefully
                options.WaitForJobsToComplete = true;
            });
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: kuchta1212/TenisRanking
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection"),
                                                             o => o.EnableRetryOnFailure()));

            services.AddDefaultIdentity <IdentityUser>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.Configure <EmailOptions>(opt =>
            {
                opt.Enabled        = Configuration.GetSection("Email").GetValue <bool>("Enabled");
                opt.SendGridKeyApi = Configuration.GetSection("Email").GetValue <string>("SendGridKeyApi");
                opt.SenderEmail    = Configuration.GetSection("Email").GetValue <string>("SenderEmail");
                opt.SenderName     = Configuration.GetSection("Email").GetValue <string>("SenderName");
            });

            services.Configure <MatchDaysLimitOptions>(opt =>
            {
                opt.Enabled   = Configuration.GetSection("MaxDaysLimitations").GetValue <bool>("Enabled");
                opt.Days      = int.Parse(Configuration.GetSection("MaxDaysLimitations").GetValue <string>("Days"));
                opt.LevelDrop = int.Parse(Configuration.GetSection("MaxDaysLimitations").GetValue <string>("LevelDrop"));
            });

            services.Configure <ConfirmationPeriodOptions>(opt =>
            {
                opt.Enabled = Configuration.GetSection("ConfirmationPeriod").GetValue <bool>("Enabled");
                opt.Hours   = int.Parse(Configuration.GetSection("ConfirmationPeriod").GetValue <string>("Hours"));
            });

            services.AddLocalization();
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("cs-CS"),
                };
                options.DefaultRequestCulture = new RequestCulture("en-US", "en-US");

                options.SupportedCultures = supportedCultures;

                options.SupportedUICultures = supportedCultures;
            });

            var jobKey = new JobKey("matchLimitJob");

            services.AddTransient <MatchCheckerJob>();
            services.AddQuartz(q =>
            {
                q.SchedulerId   = "Scheduler-Core";
                q.SchedulerName = "Scheduler-Core";
                q.UseMicrosoftDependencyInjectionScopedJobFactory();

                q.AddJob <MatchCheckerJob>(j => j
                                           .WithIdentity(jobKey)
                                           );

                q.AddTrigger(t => t
                             .WithIdentity("Cron Trigger")
                             .ForJob(jobKey)
                             .StartAt(DateBuilder.TodayAt(23, 55, 00))
                             .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
                             .WithDescription("match limit trigger")
                             );
            });

            var jobKey2 = new JobKey("confirmationPeriodJob");

            services.AddTransient <ConfirmationPeriodJob>();
            services.AddQuartz(q =>
            {
                q.SchedulerId   = "Scheduler-Core-2";
                q.SchedulerName = "Scheduler-Core-2";
                q.UseMicrosoftDependencyInjectionScopedJobFactory();

                q.AddJob <ConfirmationPeriodJob>(j => j
                                                 .WithIdentity(jobKey2)
                                                 );

                q.AddTrigger(t => t
                             .WithIdentity("Cron Trigger 2")
                             .ForJob(jobKey2)
                             .StartAt(DateBuilder.TodayAt(23, 55, 00))
                             .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
                             .WithDescription("confirmation period trigger")
                             );
            });

            services.AddQuartzServer(options =>
            {
                // when shutting down we want jobs to complete gracefully
                options.WaitForJobsToComplete = true;
            });


            services.AddTransient <IDbContextWrapper, DbContextWrapper>();
            services.AddTransient <IMatchProvider, MatchProvider.MatchProvider>();
            services.AddTransient <IEmailController, EmailController>();
            services.AddTransient <IViewMessageFactory, ViewMessageFactory>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
コード例 #11
0
        public static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                var startType = UserSettings.Default.StartType;
                if (startType == "TodayAt")
                {
                    x.Service <OutlookAppointmentService>(s =>
                    {
                        s.ConstructUsing(() => new OutlookAppointmentService());
                        s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
                        s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));

                        s.ScheduleQuartzJob(q =>
                                            q.WithJob(() =>
                                                      JobBuilder.Create <OutlookBooking>().Build())
                                            .AddTrigger(() =>
                                                        TriggerBuilder.Create()
                                                        .StartAt(DateBuilder.TodayAt
                                                                     (UserSettings.Default.ScheduleStartTime.Hours, UserSettings.Default.ScheduleStartTime.Minutes, UserSettings.Default.ScheduleStartTime.Seconds))
                                                        .WithSimpleSchedule(builder => builder
                                                                            .WithIntervalInHours(UserSettings.Default.ScheduleIntervalInHours) // Every x hours from then on. (App config)
                                                                            .RepeatForever())
                                                        .Build())
                                            );
                    });
                }
                else if (startType == "StartNow")
                {
                    x.Service <OutlookAppointmentService>(s =>
                    {
                        s.ConstructUsing(() => new OutlookAppointmentService());
                        s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
                        s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));

                        s.ScheduleQuartzJob(q =>
                                            q.WithJob(() =>
                                                      JobBuilder.Create <OutlookBooking>().Build())
                                            .AddTrigger(() =>
                                                        TriggerBuilder.Create()
                                                        .StartNow()                                  // Test trigger - Starts immediately.
                                                        .WithSimpleSchedule(builder => builder
                                                                            .WithIntervalInHours(24) // Every x hours from then on. (App config)
                                                                            .RepeatForever())
                                                        .Build())

                                            );
                    });
                }
                else
                {
                    throw new System.Exception("Invalid UserSettings.StartType: Argument not recognised.");
                }

                x.RunAsLocalSystem()
                .DependsOnEventLog()
                .StartAutomatically()
                .EnableServiceRecovery(rc => rc.RestartService(1));

                x.SetServiceName("OutlookAppointmentScheduler");
                x.SetDisplayName("OutlookAppointmentScheduler");
                x.SetDescription("OutlookAppointmentScheduler - Scheduled Outlook Appointment bookings to be sent at specified times.");
            });
        }