Пример #1
0
        public void ScheduleOneTimeJob(Type jobType, IDictionary <string, object> map, int hoursAfter = 0)
        {
            var        dataMap   = new JobDataMap(map);
            Guid       id        = Guid.NewGuid();
            string     name      = string.Format("{0}-{1}", jobType.Name, id.ToString());
            string     group     = id.ToString();
            IJobDetail jobDetail = JobBuilder.
                                   Create().
                                   OfType(jobType).
                                   WithIdentity(name, group).
                                   UsingJobData(dataMap).Build();

            if (hoursAfter == 0)
            {
                ITrigger trigger = TriggerBuilder.
                                   Create().
                                   ForJob(jobDetail).
                                   WithIdentity(name, group).
                                   WithSchedule(SimpleScheduleBuilder.Create().WithRepeatCount(0).WithInterval(TimeSpan.Zero)).
                                   StartNow().Build();
                GetScheduler().ScheduleJob(jobDetail, trigger);
            }
            else
            {
                ITrigger trigger = TriggerBuilder.
                                   Create().
                                   ForJob(jobDetail).
                                   WithIdentity(name, group).
                                   WithSchedule(SimpleScheduleBuilder.Create().WithRepeatCount(0).WithIntervalInHours(hoursAfter)).
                                   StartNow().Build();
                GetScheduler().ScheduleJob(jobDetail, trigger);
            }
        }
        private static ITrigger BuildScheduleConfiguredTrigger(string jobUid, string subscriptionName, JobSchedule schedule)
        {
            var trigger = TriggerBuilder.Create()
                          .WithIdentity(jobUid, subscriptionName)
                          .StartAt(schedule.StartAt);

            if (schedule.EndAt.HasValue)
            {
                trigger.EndAt(schedule.EndAt);
            }

            var simpleSchedule = SimpleScheduleBuilder.Create();

            if (schedule.RepeatCount > 0)
            {
                simpleSchedule.WithRepeatCount(schedule.RepeatCount);
            }

            if (schedule.RepeatInterval.HasValue)
            {
                simpleSchedule.WithInterval(schedule.RepeatInterval.Value);
            }

            trigger.WithSchedule(simpleSchedule);

            return(trigger.Build());
        }
Пример #3
0
        public override IScheduleBuilder GetScheduleBuilder()
        {
            SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
                                       .WithInterval(RepeatInterval)
                                       .WithRepeatCount(RepeatCount);

            switch (MisfireInstruction)
            {
            case Quartz.MisfireInstruction.SimpleTrigger.FireNow: sb.WithMisfireHandlingInstructionFireNow();
                break;

            case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount: sb.WithMisfireHandlingInstructionNextWithExistingCount();
                break;

            case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount: sb.WithMisfireHandlingInstructionNextWithRemainingCount();
                break;

            case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount: sb.WithMisfireHandlingInstructionNowWithExistingCount();
                break;

            case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount: sb.WithMisfireHandlingInstructionNowWithRemainingCount();
                break;
            }

            return(sb);
        }
        public async Task Consume(ConsumeContext <ScheduleMessage> context)
        {
            var correlationId = context.Message.CorrelationId.ToString("N");

            var jobKey = new JobKey(correlationId);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("ScheduleMessage: {0} at {1}", jobKey, context.Message.ScheduledTime);
            }

            var jobDetail = await CreateJobDetail(context, context.Message.Destination, jobKey).ConfigureAwait(false);

            var trigger = TriggerBuilder.Create()
                          .ForJob(jobDetail)
                          .StartAt(context.Message.ScheduledTime)
                          .WithSchedule(SimpleScheduleBuilder.Create().WithMisfireHandlingInstructionFireNow())
                          .WithIdentity(new TriggerKey(correlationId))
                          .Build();

            if (await _scheduler.CheckExists(trigger.Key).ConfigureAwait(false))
            {
                await _scheduler.RescheduleJob(trigger.Key, trigger).ConfigureAwait(false);
            }
            else
            {
                await _scheduler.ScheduleJob(jobDetail, trigger).ConfigureAwait(false);
            }
        }
Пример #5
0
        public async Task <TriggerPropertyBundle> LoadExtendedTriggerProperties(
            ConnectionAndTransactionHolder conn,
            TriggerKey triggerKey,
            CancellationToken cancellationToken = default)
        {
            using (var cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlSelectSimpleTrigger, TablePrefix)))
            {
                DbAccessor.AddCommandParameter(cmd, "schedulerName", SchedName);
                DbAccessor.AddCommandParameter(cmd, "triggerName", triggerKey.Name);
                DbAccessor.AddCommandParameter(cmd, "triggerGroup", triggerKey.Group);

                using (var rs = await cmd.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
                {
                    if (await rs.ReadAsync(cancellationToken).ConfigureAwait(false))
                    {
                        int      repeatCount    = rs.GetInt32(AdoConstants.ColumnRepeatCount);
                        TimeSpan repeatInterval = DbAccessor.GetTimeSpanFromDbValue(rs[AdoConstants.ColumnRepeatInterval]) ?? TimeSpan.Zero;
                        int      timesTriggered = rs.GetInt32(AdoConstants.ColumnTimesTriggered);

                        SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
                                                   .WithRepeatCount(repeatCount)
                                                   .WithInterval(repeatInterval);

                        string[] statePropertyNames  = { "timesTriggered" };
                        object[] statePropertyValues = { timesTriggered };

                        return(new TriggerPropertyBundle(sb, statePropertyNames, statePropertyValues));
                    }
                }
                throw new InvalidOperationException("No record found for selection of Trigger with key: '" + triggerKey + "' and statement: " + AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlSelectSimpleTrigger, TablePrefix));
            }
        }
        public void TestStoreAndRetrieveTriggers()
        {
            RAMJobStore store = new RAMJobStore();

            // Store jobs and triggers.
            for (int i = 0; i < 10; i++)
            {
                IJobDetail job = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                store.StoreJob(job, true);
                SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create();
                ITrigger trigger = TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).Build();
                store.StoreTrigger((IOperableTrigger)trigger, true);
            }
            // Retrieve job and trigger.
            for (int i = 0; i < 10; i++)
            {
                JobKey     jobKey    = JobKey.Create("job" + i);
                IJobDetail storedJob = store.RetrieveJob(jobKey);
                Assert.AreEqual(jobKey, storedJob.Key);

                TriggerKey triggerKey    = new TriggerKey("job" + i);
                ITrigger   storedTrigger = store.RetrieveTrigger(triggerKey);
                Assert.AreEqual(triggerKey, storedTrigger.Key);
            }
        }
Пример #7
0
        public static async void Start(IServiceProvider serviceProvider)
        {
            var configurationProvider = serviceProvider.GetRequiredService <IConfiguration>();
            var scheduler             = await StdSchedulerFactory.GetDefaultScheduler();

            scheduler.JobFactory = serviceProvider.GetRequiredService <JobFactory>();
            foreach (var job in GetJobsToRun(configurationProvider))
            {
                var jobDetail = JobBuilder.Create(job.Type).Build();

                var schedule = !string.IsNullOrWhiteSpace(job.CronExpression)
                    ? (IScheduleBuilder)CronScheduleBuilder.CronSchedule(job.CronExpression)
                    : SimpleScheduleBuilder.Create().WithIntervalInSeconds(DefaultStartIntervalSeconds).RepeatForever();

                var trigger = TriggerBuilder.Create()
                              .WithIdentity(job.Type.FullName)
                              .WithSchedule(schedule)
                              .StartNow()
                              .Build();

                await scheduler.ScheduleJob(jobDetail, trigger);
            }

            await scheduler.Start();
        }
Пример #8
0
        public TriggerPropertyBundle LoadExtendedTriggerProperties(ConnectionAndTransactionHolder conn, TriggerKey triggerKey)
        {
            using (IDbCommand cmd = commandAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlSelectSimpleTrigger, tablePrefix, schedNameLiteral)))
            {
                commandAccessor.AddCommandParameter(cmd, "triggerName", triggerKey.Name);
                commandAccessor.AddCommandParameter(cmd, "triggerGroup", triggerKey.Group);

                using (IDataReader rs = cmd.ExecuteReader())
                {
                    if (rs.Read())
                    {
                        int  repeatCount    = rs.GetInt32(AdoConstants.ColumnRepeatCount);
                        long repeatInterval = rs.GetInt64(AdoConstants.ColumnRepeatInterval);
                        int  timesTriggered = rs.GetInt32(AdoConstants.ColumnTimesTriggered);

                        SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
                                                   .WithRepeatCount(repeatCount)
                                                   .WithInterval(TimeSpan.FromMilliseconds(repeatInterval));

                        string[] statePropertyNames  = { "timesTriggered" };
                        object[] statePropertyValues = { timesTriggered };

                        return(new TriggerPropertyBundle(sb, statePropertyNames, statePropertyValues));
                    }
                }
                throw new InvalidOperationException("No record found for selection of Trigger with key: '" + triggerKey + "' and statement: " + AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlSelectSimpleTrigger, tablePrefix, schedNameLiteral));
            }
        }
        public async Task Consume(ConsumeContext <ScheduleMessage> context)
        {
            var correlationId = context.Message.CorrelationId.ToString("N");

            var jobKey = new JobKey(correlationId);

            var jobDetail = await CreateJobDetail(context, context.Message.Destination, jobKey, context.Message.CorrelationId).ConfigureAwait(false);

            var triggerKey = new TriggerKey(correlationId);
            var trigger    = TriggerBuilder.Create()
                             .ForJob(jobDetail)
                             .StartAt(context.Message.ScheduledTime)
                             .WithSchedule(SimpleScheduleBuilder.Create().WithMisfireHandlingInstructionFireNow())
                             .WithIdentity(triggerKey)
                             .Build();

            if (await _scheduler.CheckExists(trigger.Key, context.CancellationToken).ConfigureAwait(false))
            {
                await _scheduler.UnscheduleJob(trigger.Key, context.CancellationToken).ConfigureAwait(false);
            }

            await _scheduler.ScheduleJob(jobDetail, trigger, context.CancellationToken).ConfigureAwait(false);

            LogContext.Debug?.Log("Scheduled: {Key} {Schedule}", jobKey, trigger.GetNextFireTimeUtc());
        }
Пример #10
0
        public IScheduleBuilder GetScheduleBuilder()
        {
            var builder = SimpleScheduleBuilder.Create();

            if (this.RepeatCount < 0)
            {
                builder.RepeatForever();
            }

            builder.WithInterval(this.Interval);
            return(builder);
        }
        public async Task TestTriggerMisfiredMessage()
        {
            IOperableTrigger t = (IOperableTrigger)TriggerBuilder.Create()
                                 .WithSchedule(SimpleScheduleBuilder.Create())
                                 .Build();

            t.JobKey = new JobKey("name", "group");

            await plugin.TriggerMisfired(t);

            Assert.That(plugin.InfoMessages.Count, Is.EqualTo(1));
        }
Пример #12
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());
        }
Пример #13
0
        public TriggerPropertyBundle ReadTriggerPropertyBundle(DbDataReader rs)
        {
            int      repeatCount    = rs.GetInt32(AdoConstants.ColumnRepeatCount);
            TimeSpan repeatInterval = DbAccessor.GetTimeSpanFromDbValue(rs[AdoConstants.ColumnRepeatInterval]) ?? TimeSpan.Zero;
            int      timesTriggered = rs.GetInt32(AdoConstants.ColumnTimesTriggered);

            SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
                                       .WithRepeatCount(repeatCount)
                                       .WithInterval(repeatInterval);

            string[] statePropertyNames  = { "timesTriggered" };
            object[] statePropertyValues = { timesTriggered };

            return(new TriggerPropertyBundle(sb, statePropertyNames, statePropertyValues));
        }
        public async Task TestTriggerCompleteMessage()
        {
            ITrigger t = TriggerBuilder.Create()
                         .WithSchedule(SimpleScheduleBuilder.Create())
                         .Build();

            IJobExecutionContext ctx = new JobExecutionContextImpl(
                null,
                TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(NoOpJob), (IOperableTrigger)t),
                null);

            await plugin.TriggerComplete(t, ctx, SchedulerInstruction.ReExecuteJob);

            Assert.That(plugin.InfoMessages.Count, Is.EqualTo(1));
        }
Пример #15
0
        static void Main(string[] args)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(exceptionHandler);

            Console.TreatControlCAsInput = true;

            // TODD: move schedule setting data to configure file to make it flexible
            var scheduleFactory = new StdSchedulerFactory();
            var schedular       = scheduleFactory.GetScheduler();

            var job = JobBuilder.Create <WeatherScrapeJob>()
                      .WithIdentity(typeof(WeatherScrapeJob).GetType().Name)
                      .StoreDurably()
                      .Build();

            var simpleSchedule = SimpleScheduleBuilder.Create();

            var trigger = TriggerBuilder.Create()
                          .StartNow()
                          .WithSchedule(simpleSchedule.WithIntervalInMinutes(10).RepeatForever())
                          //.WithCronSchedule("0 0/10 * * * ?")// every 10 mins execute the job
                          .WithIdentity(typeof(WeatherScrapeJob).GetType().Name + "Tr")
                          .Build();

            schedular.ScheduleJob(job, trigger);

            schedular.Start();

            Console.WriteLine("Press [Escape (Esc)] to exit the tesing running of scrape weather job");

            ConsoleKeyInfo cki;

            do
            {
                cki = Console.ReadKey();
                // do nothing
                // blocking here
                Thread.Sleep(50);
            }while(cki.Key != ConsoleKey.Escape);

            Console.WriteLine("Waiting job shut down...");
            schedular.Shutdown(true);

            Console.WriteLine("Job shut down competed,, please press any key to exit");
            Console.ReadKey();
        }
Пример #16
0
        /// <summary>
        /// Quartz按 时 分 秒 执行
        /// </summary>
        public static void demo1()
        {
            var simpleSchedule = SimpleScheduleBuilder.Create();
            Action <SimpleScheduleBuilder> action = (x) =>
            {
                //按小时 永远执行
                //x.WithIntervalInHours(1).RepeatForever();
                ////按分钟执行 n+1次
                //x.WithIntervalInMinutes(1).WithRepeatCount(50);
                x.WithIntervalInMinutes(2).RepeatForever();
                //按分钟执行 永远执行
                //x.WithIntervalInSeconds(1).RepeatForever();
            };

            ExecutePlan.StartTime <TwoDogsJob>(action);
        }
Пример #17
0
        public async Task TestTriggerMisfiredMessage()
        {
            // arrange
            A.CallTo(() => mockLog.Log(LogLevel.Info, null, null, null)).Returns(true);
            IOperableTrigger t = (IOperableTrigger)TriggerBuilder.Create()
                                 .WithSchedule(SimpleScheduleBuilder.Create())
                                 .Build();

            t.JobKey = new JobKey("name", "group");

            // act
            await plugin.TriggerMisfired(t);

            // assert
            A.CallTo(() => mockLog.Log(A <LogLevel> .That.IsEqualTo(LogLevel.Info), A <Func <string> > .That.IsNull(), A <Exception> .That.IsNull(), A <object[]> .That.Not.IsNull())).MustHaveHappened();
        }
        public void TestTriggerMisfiredMessage()
        {
            // arrange
            mockLog.Stub(log => log.IsInfoEnabled).Return(true);
            IOperableTrigger t = (IOperableTrigger)TriggerBuilder.Create()
                                 .WithSchedule(SimpleScheduleBuilder.Create())
                                 .Build();

            t.JobKey = new JobKey("name", "group");

            // act
            plugin.TriggerMisfired(t);

            // assert
            mockLog.AssertWasCalled(log => log.Info(Arg <string> .Is.NotNull));
        }
Пример #19
0
        private void AddTask(String cityName)
        {
            // construct job info
            IJobDetail jobDetail = JobBuilder
                                   .Create()
                                   .OfType(typeof(BikeTask))
                                   .WithIdentity(new JobKey(cityName, "citiesJobs"))
                                   .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .ForJob(jobDetail)
                               .WithIdentity(new TriggerKey(cityName, "citiesTrigger"))
                               .WithSchedule(SimpleScheduleBuilder.Create().WithIntervalInSeconds(60))
                               .StartAt(DateTime.UtcNow.AddSeconds(1))
                               .Build();

            _scheduler.ScheduleJob(jobDetail, trigger);
        }
Пример #20
0
		public void ScheduleOneTimeJob(Type jobType, JobDataMap dataMap, int clientID)
		{
			string name = string.Format("{0}-{1}", jobType.Name, clientID);
			string group = clientID.ToString();
			IJobDetail jobDetail = JobBuilder.
				Create().
				OfType(jobType).
				WithIdentity(name, group).
				WithDescription("One time job").
				UsingJobData(dataMap).Build();
			ITrigger trigger = TriggerBuilder.
				Create().
				ForJob(jobDetail).
				WithIdentity(name, group).
				WithSchedule(SimpleScheduleBuilder.Create().WithRepeatCount(0).WithInterval(TimeSpan.Zero)).
				StartNow().Build();
			GetScheduler().ScheduleJob(jobDetail, trigger);
		}
Пример #21
0
        private static SimpleScheduleBuilder zCreateSimpleSchedule(Schedule schedule)
        {
            SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create();

            switch (schedule.MissedScheduleMode)
            {
            case MissedScheduleMode.RunImmediately:
                sb = sb.WithMisfireHandlingInstructionFireNow();
                break;

            case MissedScheduleMode.RunAtNextScheduledTime:
                sb = sb.WithMisfireHandlingInstructionNextWithRemainingCount();
                break;

            default:
                throw new NotSupportedException();
            }
            return(sb);
        }
        public void TestTriggerCompleteMessage()
        {
            // arrange
            mockLog.Stub(log => log.IsInfoEnabled).Return(true);

            ITrigger t = TriggerBuilder.Create()
                         .WithSchedule(SimpleScheduleBuilder.Create())
                         .Build();

            IJobExecutionContext ctx = new JobExecutionContextImpl(
                null,
                TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(NoOpJob), (IOperableTrigger)t),
                null);

            // act
            plugin.TriggerComplete(t, ctx, SchedulerInstruction.ReExecuteJob);

            // assert
            mockLog.AssertWasCalled(log => log.Info(Arg <string> .Is.NotNull));
        }
Пример #23
0
        public async Task TestTriggerCompleteMessage()
        {
            // arrange
            A.CallTo(() => mockLog.Log(LogLevel.Info, null, null, null)).Returns(true);

            ITrigger t = TriggerBuilder.Create()
                         .WithSchedule(SimpleScheduleBuilder.Create())
                         .Build();

            IJobExecutionContext ctx = new JobExecutionContextImpl(
                null,
                TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(NoOpJob), (IOperableTrigger)t),
                null);

            // act
            await plugin.TriggerComplete(t, ctx, SchedulerInstruction.ReExecuteJob);

            // assert
            A.CallTo(() => mockLog.Log(A <LogLevel> .That.IsEqualTo(LogLevel.Info), A <Func <string> > .That.IsNull(), A <Exception> .That.IsNull(), A <object[]> .That.Not.IsNull())).MustHaveHappened();
        }
        public async Task TestStoreAndRetrieveTriggers()
        {
            var store = new RavenJobStore
            {
                Database = "QuartzTest",
                Urls     = "[\"http://localhost:8080\"]"
            };
            await store.Initialize(null, fSignaler);

            await store.SchedulerStarted();

            // Store jobs and triggers.
            for (var i = 0; i < 10; i++)
            {
                var job = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                await store.StoreJob(job, true);

                var schedule = SimpleScheduleBuilder.Create();
                var trigger  = TriggerBuilder.Create().WithIdentity("trigger" + i).WithSchedule(schedule).ForJob(job)
                               .Build();
                await store.StoreTrigger((IOperableTrigger)trigger, true);
            }

            // Retrieve job and trigger.
            for (var i = 0; i < 10; i++)
            {
                var jobKey    = JobKey.Create("job" + i);
                var storedJob = await store.RetrieveJob(jobKey);

                Assert.AreEqual(jobKey, storedJob.Key);

                var      triggerKey    = new TriggerKey("trigger" + i);
                ITrigger storedTrigger = await store.RetrieveTrigger(triggerKey);

                Assert.AreEqual(triggerKey, storedTrigger.Key);
            }
        }
Пример #25
0
        public void TestBasicStorageFunctions()
        {
            NameValueCollection config = new NameValueCollection();

            config["quartz.threadPool.threadCount"] = "2";
            config["quartz.threadPool.type"]        = "Quartz.Simpl.SimpleThreadPool, Quartz";
            IScheduler sched = new StdSchedulerFactory(config).GetScheduler();

            // test basic storage functions of scheduler...

            IJobDetail job = JobBuilder.NewJob()
                             .OfType <TestJob>()
                             .WithIdentity("j1")
                             .StoreDurably()
                             .Build();

            Assert.IsFalse(sched.CheckExists(new JobKey("j1")), "Unexpected existence of job named 'j1'.");

            sched.AddJob(job, false);

            Assert.IsTrue(sched.CheckExists(new JobKey("j1")), "Expected existence of job named 'j1' but checkExists return false.");

            job = sched.GetJobDetail(new JobKey("j1"));

            Assert.IsNotNull(job, "Stored job not found!");

            sched.DeleteJob(new JobKey("j1"));

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("t1")
                               .ForJob(job)
                               .StartNow()
                               .WithSchedule(SimpleScheduleBuilder.Create()
                                             .RepeatForever()
                                             .WithIntervalInSeconds(5))
                               .Build();

            Assert.IsFalse(sched.CheckExists(new TriggerKey("t1")), "Unexpected existence of trigger named '11'.");

            sched.ScheduleJob(job, trigger);

            Assert.IsTrue(sched.CheckExists(new TriggerKey("t1")), "Expected existence of trigger named 't1' but checkExists return false.");

            job = sched.GetJobDetail(new JobKey("j1"));

            Assert.IsNotNull(job, "Stored job not found!");

            trigger = sched.GetTrigger(new TriggerKey("t1"));

            Assert.IsNotNull(trigger, "Stored trigger not found!");

            job = JobBuilder.NewJob()
                  .OfType <TestJob>()
                  .WithIdentity("j2", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t2", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .RepeatForever()
                                    .WithIntervalInSeconds(5))
                      .Build();

            sched.ScheduleJob(job, trigger);

            job = JobBuilder.NewJob()
                  .OfType <TestJob>()
                  .WithIdentity("j3", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t3", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .RepeatForever()
                                    .WithIntervalInSeconds(5))
                      .Build();

            sched.ScheduleJob(job, trigger);


            IList <string> jobGroups     = sched.GetJobGroupNames();
            IList <string> triggerGroups = sched.GetTriggerGroupNames();

            Assert.AreEqual(2, jobGroups.Count, "Job group list size expected to be = 2 ");
            Assert.AreEqual(2, triggerGroups.Count, "Trigger group list size expected to be = 2 ");

            Collection.ISet <JobKey>     jobKeys     = sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(JobKey.DefaultGroup));
            Collection.ISet <TriggerKey> triggerKeys = sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(TriggerKey.DefaultGroup));

            Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 ");
            Assert.AreEqual(1, triggerKeys.Count, "Number of triggers expected in default group was 1 ");

            jobKeys     = sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("g1"));
            triggerKeys = sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 2 ");
            Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 2 ");


            TriggerState s = sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            sched.PauseTrigger(new TriggerKey("t2", "g1"));
            s = sched.GetTriggerState(new TriggerKey("t2", "g1"));
            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED ");

            sched.ResumeTrigger(new TriggerKey("t2", "g1"));
            s = sched.GetTriggerState(new TriggerKey("t2", "g1"));
            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            Collection.ISet <string> pausedGroups = sched.GetPausedTriggerGroups();
            Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 ");

            sched.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            // test that adding a trigger to a paused group causes the new trigger to be paused also...
            job = JobBuilder.NewJob()
                  .OfType <TestJob>()
                  .WithIdentity("j4", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t4", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .RepeatForever()
                                    .WithIntervalInSeconds(5))
                      .Build();

            sched.ScheduleJob(job, trigger);

            pausedGroups = sched.GetPausedTriggerGroups();
            Assert.AreEqual(1, pausedGroups.Count, "Size of paused trigger groups list expected to be 1 ");

            s = sched.GetTriggerState(new TriggerKey("t2", "g1"));
            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED ");

            s = sched.GetTriggerState(new TriggerKey("t4", "g1"));
            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t4 expected to be PAUSED");

            sched.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            s = sched.GetTriggerState(new TriggerKey("t2", "g1"));
            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            s = sched.GetTriggerState(new TriggerKey("t4", "g1"));
            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            pausedGroups = sched.GetPausedTriggerGroups();
            Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 ");


            Assert.IsFalse(sched.UnscheduleJob(new TriggerKey("foasldfksajdflk")), "Scheduler should have returned 'false' from attempt to unschedule non-existing trigger. ");

            Assert.IsTrue(sched.UnscheduleJob(new TriggerKey("t3", "g1")), "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ");

            jobKeys     = sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("g1"));
            triggerKeys = sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 1 "); // job should have been deleted also, because it is non-durable
            Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 1 ");

            Assert.IsTrue(sched.UnscheduleJob(new TriggerKey("t1")), "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ");

            jobKeys     = sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(JobKey.DefaultGroup));
            triggerKeys = sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(TriggerKey.DefaultGroup));

            Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 "); // job should have been left in place, because it is non-durable
            Assert.AreEqual(0, triggerKeys.Count, "Number of triggers expected in default group was 0 ");
        }
Пример #26
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(MisfireExample));

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

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

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

            log.Info("------- Scheduling Jobs -----------");

            // jobs can be scheduled before start() has been called

            // get a "nice round" time a few seconds in the future...

            DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15);

            // statefulJob1 will run every three seconds
            // (but it will delay for ten seconds)
            IJobDetail job = JobBuilder.NewJob <StatefulDumbJob>()
                             .WithIdentity("statefulJob1", "group1")
                             .UsingJobData(StatefulDumbJob.ExecutionDelay, 10000L)
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(startTime)
                                     .WithSchedule(SimpleScheduleBuilder.Create()
                                                   .WithIntervalInSeconds(3)
                                                   .RepeatForever())
                                     .Build();

            DateTimeOffset ft = sched.ScheduleJob(job, trigger);

            log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, ft.ToString("r"), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));

            // statefulJob2 will run every three seconds
            // (but it will delay for ten seconds - and therefore purposely misfire after a few iterations)
            job = JobBuilder.NewJob <StatefulDumbJob>()
                  .WithIdentity("statefulJob2", "group1")
                  .UsingJobData(StatefulDumbJob.ExecutionDelay, 10000L)
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger2", "group1")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInSeconds(3)
                                    .RepeatForever()
                                    .WithMisfireHandlingInstructionNowWithExistingCount())                          // set misfire instructions
                      .Build();
            ft = sched.ScheduleJob(job, trigger);

            log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, ft.ToString("r"), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));

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

            // jobs don't start firing until start() has been called...
            sched.Start();

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

            try
            {
                // sleep for ten minutes for triggers to file....
                Thread.Sleep(TimeSpan.FromMinutes(10));
            }
            catch (ThreadInterruptedException)
            {
            }

            log.Info("------- Shutting Down ---------------------");

            sched.Shutdown(true);

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

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Пример #27
0
        private async Task TestMatchers(IScheduler scheduler)
        {
            await scheduler.Clear();

            var job = JobBuilder.Create <NoOpJob>().WithIdentity("job1", "aaabbbccc").StoreDurably().Build();
            await scheduler.AddJob(job, true);

            var schedule = SimpleScheduleBuilder.Create();
            var trigger  =
                TriggerBuilder.Create().WithIdentity("trig1", "aaabbbccc").WithSchedule(schedule).ForJob(job).Build();
            await scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create <NoOpJob>().WithIdentity("job1", "xxxyyyzzz").StoreDurably().Build();
            await scheduler.AddJob(job, true);

            schedule = SimpleScheduleBuilder.Create();
            trigger  =
                TriggerBuilder.Create().WithIdentity("trig1", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            await scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create <NoOpJob>().WithIdentity("job2", "xxxyyyzzz").StoreDurably().Build();
            await scheduler.AddJob(job, true);

            schedule = SimpleScheduleBuilder.Create();
            trigger  =
                TriggerBuilder.Create().WithIdentity("trig2", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            await scheduler.ScheduleJob(trigger);

            var jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .AnyGroup());

            jkeys.Count.Should().Be(3, "Wrong number of jobs found by anything matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("xxxyyyzzz"));

            jkeys.Count.Should().Be(2, "Wrong number of jobs found by equals matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("aaabbbccc"));

            jkeys.Count.Should().Be(1, "Wrong number of jobs found by equals matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("aa"));

            jkeys.Count.Should().Be(1, "Wrong number of jobs found by starts with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("xx"));

            jkeys.Count.Should().Be(2, "Wrong number of jobs found by starts with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("cc"));

            jkeys.Count.Should().Be(1, "Wrong number of jobs found by ends with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("zzz"));

            jkeys.Count.Should().Be(2, "Wrong number of jobs found by ends with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("bc"));

            jkeys.Count.Should().Be(1, "Wrong number of jobs found by contains with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("yz"));

            jkeys.Count.Should().Be(2, "Wrong number of jobs found by contains with matcher");

            var tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .AnyGroup());

            tkeys.Count.Should().Be(3, "Wrong number of triggers found by anything matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("xxxyyyzzz"));

            tkeys.Count.Should().Be(2, "Wrong number of triggers found by equals matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("aaabbbccc"));

            tkeys.Count.Should().Be(1, "Wrong number of triggers found by equals matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("aa"));

            tkeys.Count.Should().Be(1, "Wrong number of triggers found by starts with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("xx"));

            tkeys.Count.Should().Be(2, "Wrong number of triggers found by starts with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("cc"));

            tkeys.Count.Should().Be(1, "Wrong number of triggers found by ends with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("zzz"));

            tkeys.Count.Should().Be(2, "Wrong number of triggers found by ends with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("bc"));

            tkeys.Count.Should().Be(1, "Wrong number of triggers found by contains with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("yz"));

            tkeys.Count.Should().Be(2, "Wrong number of triggers found by contains with matcher");
        }
Пример #28
0
        /// <summary>
        /// 添加Job
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static void ScheduleJob(ScheduleJobInput input)
        {
            #region JobDetail
            JobBuilder jobBuilder = JobBuilder
                                    .Create()
                                    .OfType(Type.GetType(input.FullName + "," + input.AssemblyName, true))
                                    .WithDescription(input.JobDescription)
                                    .WithIdentity(new JobKey(input.JobName, input.JobGroup))
                                    .UsingJobData(GetJobDataMap(input));

            if (input.IsRequest)
            {
                //在服务器异常时候,重启调度之后,接着执行调度
                jobBuilder = jobBuilder.RequestRecovery();
            }
            if (input.IsSave)
            {
                //保存到数据库中
                jobBuilder.StoreDurably();
            }
            IJobDetail detail = jobBuilder.Build();
            #endregion

            #region trigger

            var triggerBuilder = TriggerBuilder
                                 .Create()
                                 .ForJob(detail);

            if (!input.ChoicedCalendar.IsNullOrEmpty())
            {
                triggerBuilder.ModifiedByCalendar(input.ChoicedCalendar);
            }
            if (!input.TriggerName.IsNullOrEmpty() && !input.TriggerGroup.IsNullOrEmpty())
            {
                triggerBuilder.WithDescription(input.TriggerDescription)
                .WithIdentity(new TriggerKey(input.TriggerName, input.TriggerGroup));
            }
            #endregion

            //是否替换
            if (input.ReplaceExists)
            {
                var triggers = new global::Quartz.Collection.HashSet <ITrigger>();
                //如果是Cron触发器
                if (input.TriggerType == "CronTriggerImpl")
                {
                    triggers.Add(triggerBuilder.WithCronSchedule(input.Cron).Build());
                }
                else
                {
                    var simpleBuilder = SimpleScheduleBuilder.Create();
                    if (input.Repeat)
                    {
                        simpleBuilder.RepeatForever();
                    }
                    simpleBuilder.WithInterval(input.Interval);
                    triggers.Add(triggerBuilder.WithSchedule(simpleBuilder).Build());
                }
                ScheduleJob(detail, triggers, true);
            }
            else
            {
                //如果是Cron触发器
                if (input.TriggerType == "CronTriggerImpl")
                {
                    ScheduleJob(detail, triggerBuilder.WithCronSchedule(input.Cron).Build());
                }
                else
                {
                    var simpleBuilder = SimpleScheduleBuilder.Create();
                    if (input.Repeat)
                    {
                        simpleBuilder.RepeatForever();
                    }
                    simpleBuilder.WithInterval(input.Interval);
                    ScheduleJob(detail, triggerBuilder.WithSchedule(simpleBuilder).Build());
                }
            }
        }
        protected virtual void ProcessInternal(string xml)
        {
            PrepForProcessing();

            ValidateXml(xml);
            MaybeThrowValidationException();

            // deserialize as object model
            XmlSerializer            xs   = new XmlSerializer(typeof(QuartzXmlConfiguration20));
            QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml));

            if (data == null)
            {
                throw new SchedulerConfigException("Job definition data from XML was null after deserialization");
            }

            //
            // Extract pre-processing commands
            //
            if (data.preprocessingcommands != null)
            {
                foreach (preprocessingcommandsType command in data.preprocessingcommands)
                {
                    if (command.deletejobsingroup != null)
                    {
                        foreach (string s in command.deletejobsingroup)
                        {
                            string deleteJobGroup = s.NullSafeTrim();
                            if (!String.IsNullOrEmpty(deleteJobGroup))
                            {
                                jobGroupsToDelete.Add(deleteJobGroup);
                            }
                        }
                    }
                    if (command.deletetriggersingroup != null)
                    {
                        foreach (string s in command.deletetriggersingroup)
                        {
                            string deleteTriggerGroup = s.NullSafeTrim();
                            if (!String.IsNullOrEmpty(deleteTriggerGroup))
                            {
                                triggerGroupsToDelete.Add(deleteTriggerGroup);
                            }
                        }
                    }
                    if (command.deletejob != null)
                    {
                        foreach (preprocessingcommandsTypeDeletejob s in command.deletejob)
                        {
                            string name  = s.name.TrimEmptyToNull();
                            string group = s.group.TrimEmptyToNull();

                            if (name == null)
                            {
                                throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified.");
                            }
                            jobsToDelete.Add(new JobKey(name, group));
                        }
                    }
                    if (command.deletetrigger != null)
                    {
                        foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger)
                        {
                            string name  = s.name.TrimEmptyToNull();
                            string group = s.group.TrimEmptyToNull();

                            if (name == null)
                            {
                                throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified.");
                            }
                            triggersToDelete.Add(new TriggerKey(name, group));
                        }
                    }
                }
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands.");
                log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands.");
                log.Debug("Found " + jobsToDelete.Count + " delete job commands.");
                log.Debug("Found " + triggersToDelete.Count + " delete trigger commands.");
            }

            //
            // Extract directives
            //
            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool overWrite = data.processingdirectives[0].overwriteexistingdata;
                log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite);
                OverWriteExistingData = overWrite;
            }
            else
            {
                log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData);
            }

            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates;
                log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates);
                IgnoreDuplicates = ignoreduplicates;
            }
            else
            {
                log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates);
            }

            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger;
                log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative);
                ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative;
            }
            else
            {
                log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger);
            }

            //
            // Extract Job definitions...
            //
            List <jobdetailType> jobNodes = new List <jobdetailType>();

            if (data.schedule != null)
            {
                foreach (var schedule in data.schedule)
                {
                    if (schedule != null)
                    {
                        if (schedule.job != null)
                        {
                            jobNodes.AddRange(schedule.job);
                        }
                    }
                }
            }

            log.Debug("Found " + jobNodes.Count + " job definitions.");

            foreach (jobdetailType jobDetailType in jobNodes)
            {
                string jobName              = jobDetailType.name.TrimEmptyToNull();
                string jobGroup             = jobDetailType.group.TrimEmptyToNull();
                string jobDescription       = jobDetailType.description.TrimEmptyToNull();
                string jobTypeName          = jobDetailType.jobtype.TrimEmptyToNull();
                bool   jobDurability        = jobDetailType.durable;
                bool   jobRecoveryRequested = jobDetailType.recover;

                Type jobType = typeLoadHelper.LoadType(jobTypeName);


                IJobDetail jobDetail = JobBuilder.Create(jobType)
                                       .WithIdentity(jobName, jobGroup)
                                       .WithDescription(jobDescription)
                                       .StoreDurably(jobDurability)
                                       .RequestRecovery(jobRecoveryRequested)
                                       .Build();

                if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null)
                {
                    foreach (entryType entry in jobDetailType.jobdatamap.entry)
                    {
                        string key   = entry.key.TrimEmptyToNull();
                        string value = entry.value.TrimEmptyToNull();
                        jobDetail.JobDataMap.Add(key, value);
                    }
                }

                if (log.IsDebugEnabled)
                {
                    log.Debug("Parsed job definition: " + jobDetail);
                }

                AddJobToSchedule(jobDetail);
            }

            //
            // Extract Trigger definitions...
            //

            List <triggerType> triggerEntries = new List <triggerType>();

            if (data.schedule != null)
            {
                foreach (var schedule in data.schedule)
                {
                    if (schedule != null && schedule.trigger != null)
                    {
                        triggerEntries.AddRange(schedule.trigger);
                    }
                }
            }

            log.Debug("Found " + triggerEntries.Count + " trigger definitions.");

            foreach (triggerType triggerNode in triggerEntries)
            {
                string triggerName        = triggerNode.Item.name.TrimEmptyToNull();
                string triggerGroup       = triggerNode.Item.group.TrimEmptyToNull();
                string triggerDescription = triggerNode.Item.description.TrimEmptyToNull();
                string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull();
                string triggerJobName     = triggerNode.Item.jobname.TrimEmptyToNull();
                string triggerJobGroup    = triggerNode.Item.jobgroup.TrimEmptyToNull();

                int triggerPriority = TriggerConstants.DefaultPriority;
                if (!triggerNode.Item.priority.IsNullOrWhiteSpace())
                {
                    triggerPriority = Convert.ToInt32(triggerNode.Item.priority);
                }

                DateTimeOffset triggerStartTime = SystemTime.UtcNow();
                if (triggerNode.Item.Item != null)
                {
                    if (triggerNode.Item.Item is DateTime)
                    {
                        triggerStartTime = new DateTimeOffset((DateTime)triggerNode.Item.Item);
                    }
                    else
                    {
                        triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item));
                    }
                }

                DateTime?triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?)null;

                IScheduleBuilder sched;

                if (triggerNode.Item is simpleTriggerType)
                {
                    simpleTriggerType simpleTrigger        = (simpleTriggerType)triggerNode.Item;
                    string            repeatCountString    = simpleTrigger.repeatcount.TrimEmptyToNull();
                    string            repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull();

                    int      repeatCount    = ParseSimpleTriggerRepeatCount(repeatCountString);
                    TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString));

                    sched = SimpleScheduleBuilder.Create()
                            .WithInterval(repeatInterval)
                            .WithRepeatCount(repeatCount);

                    if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((SimpleScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction));
                    }
                }
                else if (triggerNode.Item is cronTriggerType)
                {
                    cronTriggerType cronTrigger    = (cronTriggerType)triggerNode.Item;
                    string          cronExpression = cronTrigger.cronexpression.TrimEmptyToNull();
                    string          timezoneString = cronTrigger.timezone.TrimEmptyToNull();

                    TimeZoneInfo tz = timezoneString != null?TimeZoneInfo.FindSystemTimeZoneById(timezoneString) : null;

                    sched = CronScheduleBuilder.CronSchedule(cronExpression)
                            .InTimeZone(tz);

                    if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((CronScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction));
                    }
                }
                else if (triggerNode.Item is calendarIntervalTriggerType)
                {
                    calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType)triggerNode.Item;
                    string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull();

                    IntervalUnit intervalUnit   = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull());
                    int          repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString);

                    sched = CalendarIntervalScheduleBuilder.Create()
                            .WithInterval(repeatInterval, intervalUnit);

                    if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((CalendarIntervalScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction));
                    }
                }
                else
                {
                    throw new SchedulerConfigException("Unknown trigger type in XML configuration");
                }

                IMutableTrigger trigger = (IMutableTrigger)TriggerBuilder.Create()
                                          .WithIdentity(triggerName, triggerGroup)
                                          .WithDescription(triggerDescription)
                                          .ForJob(triggerJobName, triggerJobGroup)
                                          .StartAt(triggerStartTime)
                                          .EndAt(triggerEndTime)
                                          .WithPriority(triggerPriority)
                                          .ModifiedByCalendar(triggerCalendarRef)
                                          .WithSchedule(sched)
                                          .Build();

                if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null)
                {
                    foreach (entryType entry in triggerNode.Item.jobdatamap.entry)
                    {
                        string key   = entry.key.TrimEmptyToNull();
                        string value = entry.value.TrimEmptyToNull();
                        trigger.JobDataMap.Add(key, value);
                    }
                }

                if (log.IsDebugEnabled)
                {
                    log.Debug("Parsed trigger definition: " + trigger);
                }

                AddTriggerToSchedule(trigger);
            }
        }
Пример #30
0
        public virtual void Run(bool inClearJobs, bool inScheduleJobs)
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"]    = "TestScheduler";
            properties["quartz.scheduler.instanceId"]      = "instance_one";
            properties["quartz.threadPool.type"]           = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]    = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";
            properties["quartz.jobStore.misfireThreshold"] = "60000";
            properties["quartz.jobStore.type"]             = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.useProperties"]    = "false";
            properties["quartz.jobStore.dataSource"]       = "default";
            properties["quartz.jobStore.tablePrefix"]      = "QRTZ_";
            properties["quartz.jobStore.clustered"]        = "true";
            // if running SQLite we need this
            // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";

            properties["quartz.dataSource.default.connectionString"] = "Server=(local);Database=quartz;Trusted_Connection=True;";
            properties["quartz.dataSource.default.provider"]         = "SqlServer-20";

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

            if (inClearJobs)
            {
                log.Warn("***** Deleting existing jobs/triggers *****");
                sched.Clear();
            }

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

            if (inScheduleJobs)
            {
                log.Info("------- Scheduling Jobs ------------------");

                string schedId = sched.SchedulerInstanceId;

                int count = 1;


                IJobDetail job = JobBuilder.NewJob <SimpleRecoveryJob>()
                                 .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                                 .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                                 .Build();


                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                         .WithIdentity("triger_" + count, schedId)
                                         .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                                         .WithSchedule(SimpleScheduleBuilder.Create()
                                                       .WithRepeatCount(20)
                                                       .WithInterval(TimeSpan.FromSeconds(5)))
                                         .Build();

                log.InfoFormat("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds);

                count++;


                job = JobBuilder.NewJob <SimpleRecoveryJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(2, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromSeconds(5)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));
                sched.ScheduleJob(job, trigger);

                count++;


                job = JobBuilder.NewJob <SimpleRecoveryStatefulJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromSeconds(3)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));
                sched.ScheduleJob(job, trigger);

                count++;

                job = JobBuilder.NewJob <SimpleRecoveryJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromSeconds(4)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} & repeat: {2}/{3}", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval));
                sched.ScheduleJob(job, trigger);

                count++;


                job = JobBuilder.NewJob <SimpleRecoveryJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromMilliseconds(4500)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} & repeat: {2}/{3}", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval));
                sched.ScheduleJob(job, trigger);
            }

            // jobs don't start firing until start() has been called...
            log.Info("------- Starting Scheduler ---------------");
            sched.Start();
            log.Info("------- Started Scheduler ----------------");

            log.Info("------- Waiting for one hour... ----------");

            Thread.Sleep(TimeSpan.FromHours(1));


            log.Info("------- Shutting Down --------------------");
            sched.Shutdown();
            log.Info("------- Shutdown Complete ----------------");
        }