Example #1
0
        public async Task DeleteTrigger()
        {
            IJobDetail jobDetail = JobBuilder.Create <TestJob>().WithIdentity("testjob3").StoreDurably().Build();
            ITrigger   trigger   = TriggerBuilder.Create()
                                   .WithIdentity("testjob3")
                                   .WithSchedule(CronScheduleBuilder.CronSchedule("* * * * * ?"))
                                   .Build();
            await scheduler.ScheduleJob(jobDetail, trigger);

            await ModifyStoredJobClassName();

            await scheduler.UnscheduleJob(trigger.Key);
        }
Example #2
0
        private void btnTest1_Click(object sender, EventArgs e)
        {
            HolidayCalendar cal = new HolidayCalendar();

            cal.AddExcludedDate(DateTime.UtcNow);

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

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


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

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

            // .. schedule job with trigger


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



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


            // .. schedule job with trigger2



            sched.ScheduleJob(job, t);
            sched.ScheduleJob(job, t2);
        }
Example #3
0
        private void DefinirAgendamentoExecucao()
        {
            RegistroLog.RegistarLogInfo(Mensagem.SistemaAgendamentoInicio);

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            ITrigger          trigger;

            this.scheduler = schedFact.GetScheduler();
            //this.scheduler.Start();

            IJobDetail job = JobBuilder.Create <FrmArquivoDataSUS>()
                             .WithIdentity("JobAplicacao", "groupAplicacao")
                             .Build();


            if (this.gbxAcadaMinuto.Enabled)
            {
                trigger = TriggerBuilder.Create()
                          .StartNow()
                          .WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(Convert.ToInt32(this.nudCadaMinuto.Value.ToString())))
                          .Build();
            }
            else
            {
                CronScheduleBuilder cronScheduleBuilder;

                Enumeradores.DiaDaSemana dia = Enumeradores.ConverterObject2DiaDaSemana(this.ddlDiaAgendamento.SelectedValue);

                if (dia == Enumeradores.DiaDaSemana.AllDays)
                {
                    cronScheduleBuilder = CronScheduleBuilder.DailyAtHourAndMinute(Convert.ToInt32(this.nudHora.Value), Convert.ToInt32(this.nudMinuto.Value));
                }
                else
                {
                    cronScheduleBuilder = CronScheduleBuilder.WeeklyOnDayAndHourAndMinute((DayOfWeek)dia, Convert.ToInt32(this.nudHora.Value), Convert.ToInt32(this.nudMinuto.Value));
                }

                trigger = TriggerBuilder.Create()
                          .StartNow()
                          .WithSchedule(cronScheduleBuilder)
                          .Build();
            }

            this.scheduler.ScheduleJob(job, trigger);
            this.scheduler.Start();

            this.lblUltimaExecucao.Text  = "--/--/---- --:--:--";
            this.lblProximaExecucao.Text = trigger.GetNextFireTimeUtc().Value.LocalDateTime.ToString(Constantes.FormatoDataHora);

            RegistroLog.RegistarLogInfo(Mensagem.SistemaAgendamentoFim);
        }
Example #4
0
        private void InitSchedules <T>(string[] schedules, IJobDetail job) where T : IJob
        {
            _scheduler.AddJob(job, false);

            foreach (var schedule in schedules)
            {
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithSchedule(CronScheduleBuilder.CronSchedule(schedule))
                                   .ForJob(job)
                                   .Build();

                _scheduler.ScheduleJob(trigger);
            }
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            IScheduler scheduler;

            scheduler = new StdSchedulerFactory().GetScheduler().Result;
            scheduler.Start();
            IJobDetail job = JobBuilder.Create <AutoBackupJob>().Build();

            // 创建一个触发器
            ITrigger trigger = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(17, 00))
                               .Build();

            scheduler.ScheduleJob(job, trigger);
        }
Example #6
0
        /// <summary>
        /// 立即执行
        /// </summary>
        /// <returns></returns>
        public bool StartJob(int id)
        {
            var jobInfo = _jobDetailRepository.FirstOrDefault(x => x.Id == id);

            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.CronSchedule(jobInfo.Cron);
            var      triggerKey = CreateTriggerKey(jobInfo.TriggerName, jobInfo.TriggerGroupName);
            ITrigger trigger    = TriggerBuilder.Create().StartNow()
                                  .WithIdentity(jobInfo.TriggerName, jobInfo.TriggerGroupName)
                                  .WithSchedule(scheduleBuilder.WithMisfireHandlingInstructionFireAndProceed())
                                  .Build();

            _scheduler.RescheduleJob(triggerKey, trigger);
            return(true);
        }
Example #7
0
        public static void ScheduleSendMagnitude(ushort DeviceID, CronScheduleBuilder Cron, byte Magnitude)
        {
            IJobDetail sendMagnitudeJob = JobBuilder.Create <SendMagnitude>()
                                          .UsingJobData("DeviceID", DeviceID)
                                          .UsingJobData("Magnitude", Magnitude)
                                          .Build();

            ITrigger sendMagnitudeTrigger = TriggerBuilder.Create()
                                            .WithSchedule(Cron)
                                            .ForJob(sendMagnitudeJob)
                                            .Build();

            Scheduler.ScheduleJob(sendMagnitudeJob, sendMagnitudeTrigger);
        }
        public void ReplaceJobDetail()
        {
            IJobDetail jobDetail = JobBuilder.Create <TestJob>().WithIdentity("testjob3").StoreDurably().Build();
            ITrigger   trigger   = TriggerBuilder.Create()
                                   .WithIdentity("testjob3")
                                   .WithSchedule(CronScheduleBuilder.CronSchedule("* * * * * ?"))
                                   .Build();

            scheduler.ScheduleJob(jobDetail, trigger);
            ModifyStoredJobClassName();

            jobDetail = JobBuilder.Create <TestJob>().WithIdentity("testjob3").StoreDurably().Build();
            scheduler.AddJob(jobDetail, true);
        }
        public async Task <IActionResult> Create_schedule(string time, string timem, List <string> list_Idtestcase, int id_url)
        {
            Test_schedule test_Schedule = new Test_schedule();

            test_Schedule.CreatedDate = DateTime.Now;
            string scheduleId = Guid.NewGuid().ToString("N");

            test_Schedule.id_schedule = scheduleId;
            var id_user = _userManager.GetUserId(User);

            test_Schedule.id_user         = id_user;
            test_Schedule.job_repeat_time = time + ":" + timem;
            test_Schedule.status          = "running";
            _context.Test_schedule.Add(test_Schedule);
            await _context.SaveChangesAsync();

            foreach (var id in list_Idtestcase)
            {
                Testcase_scheduled testcase_Scheduled = new Testcase_scheduled();
                testcase_Scheduled.id_schedule = scheduleId;
                testcase_Scheduled.id_url      = id_url;
                testcase_Scheduled.id_testcase = id;

                _context.Testcase_scheduled.Add(testcase_Scheduled);
            }
            _context.SaveChanges();
            IJobDetail job = JobBuilder.Create <RunTestcaseJob>()
                             .UsingJobData("scheduleid", scheduleId)
                             .WithIdentity(scheduleId, id_user)
                             .StoreDurably()
                             .RequestRecovery()
                             .Build();

            await _scheduler.AddJob(job, true);

            ITrigger trigger = TriggerBuilder.Create()
                               .ForJob(job)
                               //.UsingJobData("triggerparam", "Simple trigger 1 Parameter")
                               .WithIdentity(scheduleId + "trigger", id_user)
                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(int.Parse(time), int.Parse(timem)))
                               //                                 .StartNow()
                               //                                 .WithSimpleSchedule(z => z.WithIntervalInSeconds(600).RepeatForever())
                               .Build();


            await _scheduler.ScheduleJob(trigger);

            StatusMessage = "Create schedule successfully";
            return(RedirectToAction("Index"));
        }
Example #10
0
        public TriggerPropertyBundle ReadTriggerPropertyBundle(DbDataReader rs)
        {
            var cronExpr   = rs.GetString(AdoConstants.ColumnCronExpression) !;
            var timeZoneId = rs.GetString(AdoConstants.ColumnTimeZoneId);

            CronScheduleBuilder cb = CronScheduleBuilder.CronSchedule(cronExpr);

            if (timeZoneId != null)
            {
                cb.InTimeZone(TimeZoneUtil.FindTimeZoneById(timeZoneId));
            }

            return(new TriggerPropertyBundle(cb));
        }
Example #11
0
        public async void AddJob <T>(string name, string group, string cron) where T : IJob
        {
            IJobDetail job = JobBuilder.Create <T>()
                             .WithIdentity(name, group)
                             .Build();

            ITrigger jobTrigger = TriggerBuilder.Create()
                                  .WithIdentity(name + "Trigger", group)
                                  .WithSchedule(CronScheduleBuilder.CronSchedule(cron))
                                  .StartNow()
                                  .Build();

            await Scheduler.ScheduleJob(job, jobTrigger);
        }
Example #12
0
        public void Start()
        {
            errorWriting = new ErrorLogging();
            errorWriting.WriteErrorLog("Service has started on " + Environment.MachineName);

            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["CoreContext"];

            dataAccess = new cDataAccess(setting.ConnectionString);


            bool success = dataAccess.getImagePath(Environment.MachineName, out mImagePath);

            if (!success)
            {
                errorWriting.WriteErrorLog("Invalid Image path. Please check the computer name!");
                Stop();
            }

            try
            {
                _scheduler = StdSchedulerFactory.GetDefaultScheduler();

                _scheduler.Start();

                // define the job and tie it to our HelloJob class
                IJobDetail job = JobBuilder.Create <ProcessJob>()
                                 .Build();

                IJobDetail job2 = JobBuilder.Create <ProcessJob>()
                                  .Build();

                // Trigger the job to run now, and then repeat 0
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(6, 0))
                                   .Build();

                // Tell quartz to schedule the job using our trigger
                _scheduler.ScheduleJob(job, trigger);

                ITrigger trigger2 = TriggerBuilder.Create()
                                    .StartNow()
                                    .Build();

                _scheduler.ScheduleJob(job2, trigger2);
            }
            catch (SchedulerException ex)
            {
                errorWriting.WriteErrorLog(ex.Message);
            }
        }
Example #13
0
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

            scheduler.Start();
            IJobDetail job = JobBuilder.Create <AuctionChecker>().Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger", "groupForCheck")
                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(00, 00))
                               .Build();

            scheduler.ScheduleJob(job, trigger);
        }
Example #14
0
        private ITrigger GetTrigger(IJobDetail jobDetail)
        {
            TriggerBuilder builder = TriggerBuilder
                                     .Create()
                                     .ForJob(jobDetail)
                                     .WithDescription(txtTriggerDescription.Text.Trim())
                                     .WithIdentity(new TriggerKey(txtTriggerName.Text.Trim(), txtTriggerGroup.Text.Trim()));

            if (cboTriggerType.SelectedText == "Simple")
            {
                return(builder.WithSchedule(SimpleScheduleBuilder.Create()).Build());
            }
            return(builder.WithSchedule(CronScheduleBuilder.CronSchedule(txtCronExpression.Text)).Build());
        }
        public async Task <ITrigger> FillTriggerAsync(Services.Notification.NotificationSchedule value)
        {
            DayOfWeek[] weekDays = new DayOfWeek[7];

            int i = 0;

            if (value.RunOnSunday)
            {
                weekDays[i++] = DayOfWeek.Sunday;
            }
            if (value.RunOnMonday)
            {
                weekDays[i++] = DayOfWeek.Monday;
            }
            if (value.RunOnTuesday)
            {
                weekDays[i++] = DayOfWeek.Tuesday;
            }
            if (value.RunOnWednesday)
            {
                weekDays[i++] = DayOfWeek.Wednesday;
            }
            if (value.RunOnThursday)
            {
                weekDays[i++] = DayOfWeek.Thursday;
            }
            if (value.RunOnFriday)
            {
                weekDays[i++] = DayOfWeek.Friday;
            }
            if (value.RunOnSaturday)
            {
                weekDays[i++] = DayOfWeek.Saturday;
            }

            if (await Scheduler.CheckExists(new TriggerKey(value.SubscriberID, value.NotificationType)) == true)
            {
                await Scheduler.DeleteJob(new JobKey(value.SubscriberID, value.NotificationType));
            }
            var k       = new TriggerKey(value.SubscriberID, value.NotificationType);
            var trigger = TriggerBuilder.Create()
                          .WithIdentity(k)
                          .WithSchedule(CronScheduleBuilder
                                        .AtHourAndMinuteOnGivenDaysOfWeek(value.RunOnHour, value.RunOnMinute, weekDays.Take(i).ToArray()))
                          .ForJob(new JobKey(value.NotificationType))
                          .Build();

            return(trigger);
        }
Example #16
0
        /// <summary>
        /// 开启自动备份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartAutobutton_Click_1(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(backupPathbox.Text))
            {
                MessageBox.Show(@"请选择保存路径");
                return;
            }

            ButtonNo(sender, true);
            TextBoxNo(sender, true);
            var text = StartAutobutton.Text;

            if (text == "开启自动备份")
            {
                if (!ConnectionDatabase(GetDbName(), sender))
                {
                    return;
                }
                this.textBox1.Text += System.Environment.NewLine + $@"时间:{DateTime.Now:yyyy-MM--dd hh:mm},开启自动备份...";
            }
            else
            {
                this.textBox1.Text += System.Environment.NewLine + $@"时间:{DateTime.Now:yyyy-MM--dd hh:mm},关闭自动备份...:";
            }
            StartAutobutton.Text = text == "关闭自动备份" ? "开启自动备份" : "关闭自动备份";

            try
            {
                StaticForm1 = this;
                IScheduler      scheduler    = new StdSchedulerFactory().GetScheduler();
                JobDetailImpl   jdBossReport = new JobDetailImpl("Backup", typeof(Backups));
                IMutableTrigger trigger      = CronScheduleBuilder.DailyAtHourAndMinute(Convert.ToInt16(HourText.Text), Convert.ToInt16(MinuteText.Text)).Build();
                trigger.Key = new TriggerKey("AutoBackups");
                if (StartAutobutton.Text == @"开启自动备份")
                {
                    scheduler.Shutdown();
                    ButtonNo(sender, false);
                    TextBoxNo(sender, false);
                    return;
                }
                scheduler.ScheduleJob(jdBossReport, trigger);
                scheduler.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"未知错误 请重试");
                return;
            }
        }
        private void DefinirAgendamentoExecucao()
        {
            RegistroLog.RegistarLogInfo(Mensagem.SistemaAgendamentoInicio);

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            ITrigger          trigger;

            this.scheduler = schedFact.GetScheduler();

            IJobDetail job = JobBuilder.Create <ServicoArquivosDataSUS>()
                             .WithIdentity("JobServico", "groupServico")
                             .Build();


            if (this.executarAcadaMinuto > 0)
            {
                trigger = TriggerBuilder.Create()
                          .StartNow()
                          .WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(this.executarAcadaMinuto))
                          .Build();
            }
            else
            {
                CronScheduleBuilder cronScheduleBuilder;

                Enumeradores.DiaDaSemana dia = Enumeradores.ConverterObject2DiaDaSemana(this.diaAgendamento);

                if (dia == Enumeradores.DiaDaSemana.AllDays)
                {
                    cronScheduleBuilder = CronScheduleBuilder.DailyAtHourAndMinute(this.hora, this.minuto);
                }
                else
                {
                    cronScheduleBuilder = CronScheduleBuilder.WeeklyOnDayAndHourAndMinute((DayOfWeek)dia, this.hora, this.minuto);
                }

                trigger = TriggerBuilder.Create()
                          .StartNow()
                          .WithSchedule(cronScheduleBuilder)
                          .Build();
            }

            this.scheduler.ScheduleJob(job, trigger);
            this.scheduler.Start();

            RegistroLog.RegistarLogInfo(Mensagem.ServicoProximaExecucao + " - " + trigger.GetNextFireTimeUtc().Value.LocalDateTime.ToString(Constantes.FormatoDataHora));

            RegistroLog.RegistarLogInfo(Mensagem.SistemaAgendamentoFim);
        }
Example #18
0
        private ITrigger?GenTrigger(TriggerKey triggerKey, DateTime startTime, uint interval, string cronExpression,
                                    bool onceJob = false)
        {
            if (onceJob && startTime != default)
            {
                Console.WriteLine("will start job at time: {0}", startTime);
                return(TriggerBuilder.Create()
                       .WithIdentity(triggerKey)
                       .StartAt(new DateTimeOffset(new DateTime(startTime.Year, startTime.Month, startTime.Day,
                                                                startTime.Hour, startTime.Minute, startTime.Second)))
                       .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionNextWithRemainingCount())
                       .Build());
            }

            if (startTime != default)
            {
                return(TriggerBuilder.Create()
                       .WithIdentity(triggerKey)
                       .StartNow()
                       .WithSchedule(
                           CronScheduleBuilder.DailyAtHourAndMinute(startTime.Hour,
                                                                    startTime.Minute)) //未指定错过执行时间的处理方式,要求job里面的逻辑支持可重入
                       .Build());
            }
            if (interval != 0)
            {
                //pause后重新resume,执行类似misfire job的原因
                //http://stackoverflow.com/questions/1933676/quartz-java-resuming-a-job-excecutes-it-many-times
                return(TriggerBuilder.Create()
                       .WithIdentity(triggerKey)
                       .WithSimpleSchedule(x => x
                                           .WithIntervalInSeconds((int)interval)
                                           .RepeatForever()
                                           .WithMisfireHandlingInstructionNextWithRemainingCount() //discard misfire trigger
                                           )
                       .StartNow()
                       .Build());
            }
            if (!string.IsNullOrEmpty(cronExpression))
            {
                return(TriggerBuilder.Create()
                       .WithIdentity(triggerKey)
                       .StartNow()
                       .WithCronSchedule(cronExpression)
                       .Build());
            }

            return(null);
        }
Example #19
0
        /// <summary>
        /// 初始化定时任务
        /// </summary>
        private static void InitScheduleTask()
        {
            try
            {
                _logger.Info("初始化定时任务开始。");
                int    hour     = 12;
                int    minute   = 00;
                string taskTime = ConfigHelper.GetAppConfig("taskTime");
                if ("".Equals(taskTime))
                {
                    _logger.Warn("未配置每天自动执行时间。");
                }
                else
                {
                    string[] times = taskTime.Split(':');
                    if (null != times && times.Length > 0)
                    {
                        hour   = int.Parse(times[0]);
                        minute = int.Parse(times[1]);
                    }
                }
                //1.首先创建一个作业调度池
                ISchedulerFactory schedf = new StdSchedulerFactory();
                IScheduler        sched  = schedf.GetScheduler();
                //2.创建出来一个具体的作业
                IJobDetail job = JobBuilder.Create <NotifyJob>().Build();
                //3.创建并配置一个触发器
                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create().WithSimpleSchedule(x => x.WithIntervalInSeconds(3).WithRepeatCount(int.MaxValue)).Build();

                ITrigger trigger2 = TriggerBuilder.Create()
                                    .WithIdentity("myTrigger", "group2")
                                    .ForJob(job)
                                    .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(hour, minute)) // 每天9:30执行一次
                                                                                                          //.ModifiedByCalendar("myHolidays") // but not on holidays 设置那一天不知道
                                    .Build();

                //4.加入作业调度池中
                sched.ScheduleJob(job, trigger2);
                //5.开始运行
                sched.Start();
                //QuartzManager.AddJob<TaskJob>("每隔5秒", "*/5 * * * * ?");//每隔5秒执行一次这个方法
                _logger.Info("初始化定时任务成功,每天执行时间:" + taskTime);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                _logger.Error("初始化定时任务时发生异常:" + ex.Message + ex.StackTrace);
            }
        }
Example #20
0
        /// <summary>
        /// Schedule job base on cron expression
        /// </summary>
        /// <param name="jobName">Job to be schedule</param>
        /// <param name="jobGroup">Job group</param>
        /// <param name="cronExpression">Cron expression</param>
        /// <param name="name">Name of trigger</param>
        public void ScheduleJobCronExpression(string jobName, string jobGroup, string cronExpression, string name)
        {
            var jobKey  = new JobKey(jobName, jobGroup);
            var trigger = TriggerBuilder.Create()
                          .WithIdentity(name)
                          .ForJob(jobKey)
                          .StartNow()
                          .WithSchedule(CronScheduleBuilder.CronSchedule(cronExpression))
                          .Build();

            if (!scheduler.CheckExists(trigger.Key).Result)
            {
                scheduler.ScheduleJob(trigger);
            }
        }
Example #21
0
        private void StartQuartz()
        {
            IScheduler sched = new StdSchedulerFactory().GetScheduler();

            //==============BossReportJob 开始================
            JobDetailImpl   jdBossReport      = new JobDetailImpl("jdBossReportJob", typeof(BossReportJob));
            IMutableTrigger triggerBossReport = CronScheduleBuilder.DailyAtHourAndMinute(23, 45).Build();//每天23:45执行一次

            triggerBossReport.Key = new TriggerKey("triggerBossReportJob");
            sched.ScheduleJob(jdBossReport, triggerBossReport);
            //==============BossReportJob 结束================


            sched.Start();
        }
Example #22
0
        public void Start()
        {
            //从配置文件中读取任务启动时间
            string     cronExpr = ConfigurationManager.AppSettings["cronExpr"];
            IJobDetail job      = JobBuilder.Create <StartJob>().WithIdentity("job1", "group1").Build();
            //创建任务运行的触发器
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("triggger1", "group1")
                               .WithSchedule(CronScheduleBuilder.CronSchedule(new CronExpression(cronExpr)))
                               .Build();

            //启动任务
            _scheduler.ScheduleJob(job, trigger);
            _scheduler.Start();
        }
        public void TestAtHourAndMinuteOnGivenDaysOfWeek()
        {
            var trigger = (ICronTrigger)TriggerBuilder.Create()
                          .WithIdentity("test")
                          .WithSchedule(CronScheduleBuilder.AtHourAndMinuteOnGivenDaysOfWeek(10, 0, DayOfWeek.Monday, DayOfWeek.Thursday, DayOfWeek.Friday))
                          .Build();

            Assert.AreEqual("0 0 10 ? * 2,5,6", trigger.CronExpressionString);

            trigger = (ICronTrigger)TriggerBuilder.Create().WithIdentity("test")
                      .WithSchedule(CronScheduleBuilder.AtHourAndMinuteOnGivenDaysOfWeek(10, 0, DayOfWeek.Wednesday))
                      .Build();

            Assert.AreEqual("0 0 10 ? * 4", trigger.CronExpressionString);
        }
        public static void Start2()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

            scheduler.Start();

            IJobDetail job = JobBuilder.Create <QuartzJob>().Build();

            ITrigger trigger = TriggerBuilder.Create()

                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(17, 48))
                               .Build();

            scheduler.ScheduleJob(job, trigger);
        }
Example #25
0
        private void UpdateScheduledSettings(ScheduledJobsSettings settings)
        {
            settings.PlexAvailabilityChecker  = 60;
            settings.SickRageCacher           = 60;
            settings.SonarrCacher             = 60;
            settings.CouchPotatoCacher        = 60;
            settings.StoreBackup              = 24;
            settings.StoreCleanup             = 24;
            settings.UserRequestLimitResetter = 12;
            settings.PlexEpisodeCacher        = 12;

            var cron = (Quartz.Impl.Triggers.CronTriggerImpl)CronScheduleBuilder.WeeklyOnDayAndHourAndMinute(DayOfWeek.Friday, 7, 0).Build();

            settings.RecentlyAddedCron = cron.CronExpressionString; // Weekly CRON at 7 am on Mondays
        }
        public static void StartCronJob <TJob>(IScheduler scheduler, string cron)
            where TJob : IJob
        {
            var jobName = typeof(TJob).FullName;
            var job     = JobBuilder.Create <TJob>()
                          .WithIdentity(jobName)
                          .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity($"{jobName}.trigger")
                          .WithSchedule(CronScheduleBuilder.CronSchedule(cron))
                          .Build();

            scheduler.ScheduleJob(job, trigger);
        }
        public static void Start()
        {
            var job     = new JobDetailImpl(nameof(BJTTOperationSyncJob), typeof(BJTTOperationSyncJob));
            var trigger = CronScheduleBuilder.CronSchedule(new CronExpression(Global.AppSettings["BJTT"]["OperationSyncScheduler"].Value <string>())).Build();

            trigger.Key = new TriggerKey($"{nameof(BJTTOperationSyncScheduler)}-{nameof(trigger)}");

            var scheduler = new StdSchedulerFactory().GetScheduler();

            scheduler.ScheduleJob(job, trigger);
            scheduler.Start();
            Global.SchedulerLogger.Info($"{nameof(BJTTOperationSyncScheduler)} Started");

            System.Threading.Tasks.Task.Run(() => new BJTTOperationSyncJob().Execute(null));
        }
Example #28
0
        public static async void Start(IServiceProvider serviceProvider)
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            scheduler.JobFactory = serviceProvider.GetService <JobFactory>();
            await scheduler.Start();

            IJobDetail jobDetail = JobBuilder.Create <DataJob>().Build();
            ITrigger   trigger   = TriggerBuilder.Create()
                                   .WithIdentity("MailingTrigger", "default")
                                   .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(15, 00))
                                   .Build();

            await scheduler.ScheduleJob(jobDetail, trigger);
        }
Example #29
0
        public override IScheduleBuilder GetScheduleBuilder()
        {
            CronScheduleBuilder cb = CronScheduleBuilder.CronSchedule(CronExpressionString).InTimeZone(TimeZone);

            switch (MisfireInstruction)
            {
            case Quartz.MisfireInstruction.CronTrigger.DoNothing: cb.WithMisfireHandlingInstructionDoNothing();
                break;

            case Quartz.MisfireInstruction.CronTrigger.FireOnceNow: cb.WithMisfireHandlingInstructionFireAndProceed();
                break;
            }

            return(cb);
        }
Example #30
0
        private QuartzManager()
        {
            logger = LogManager.GetCurrentClassLogger();


            var properties = new NameValueCollection();

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

            // 设置线程池
            properties["quartz.threadPool.type"]           = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]    = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // 远程输出配置
            properties["quartz.scheduler.exporter.type"]        = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
            properties["quartz.scheduler.exporter.port"]        = "555";
            properties["quartz.scheduler.exporter.bindName"]    = "QuartzScheduler";
            properties["quartz.scheduler.exporter.channelType"] = "tcp";

            // 1.创建作业调度池(Scheduler)
            //scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;

            var schedulerFactory = new StdSchedulerFactory(properties);

            scheduler = schedulerFactory.GetScheduler().Result;

            // 2.创建一个具体的作业即job (具体的job需要单独在一个文件中执行)
            var job = JobBuilder.Create <PrintTimeJob>().Build();

            // 3.创建并配置一个触发器即trigger,10s执行一次。重复3次
            var trigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithIntervalInSeconds(10).WithRepeatCount(2)).Build();

            // 4.将job和trigger加入到作业调度池中
            scheduler.ScheduleJob(job, trigger);

            #region 打印时间任务2 [PrintTimeJob2]
            var printTime2Job = JobBuilder.Create <PrintTimeJob2>()
                                .WithIdentity("printTime2Job", "PrintTimeGroup")
                                .Build();
            var printTime2Trigger = TriggerBuilder.Create()
                                    .WithIdentity("printTime2Job", "PrintTimeGroup")
                                    .StartNow()
                                    .WithSchedule(CronScheduleBuilder.CronSchedule("0 0/5 * * * ?")) // 每5分钟执行一次
                                    .Build();
            scheduler.ScheduleJob(printTime2Job, printTime2Trigger);
            #endregion
        }