Пример #1
0
		public void TestSameDefaultPriority()
		{
            NameValueCollection config = new NameValueCollection();
		    config["quartz.threadPool.threadCount"] = "1";
		    config["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool";

            IScheduler sched = new StdSchedulerFactory(config).GetScheduler();
            
			DateTime n = DateTime.UtcNow;
			DateTime cal = new DateTime(n.Year, n.Month, n.Day, n.Hour, n.Minute, 1, n.Millisecond);

            IMutableTrigger trig1 = new SimpleTriggerImpl("T1", null, cal);
            IMutableTrigger trig2 = new SimpleTriggerImpl("T2", null, cal);

			JobDetailImpl jobDetail = new JobDetailImpl("JD", null, typeof (TestJob));

			sched.ScheduleJob(jobDetail, trig1);

			trig2.JobKey = new JobKey(jobDetail.Key.Name);
			sched.ScheduleJob(trig2);

			sched.Start();

			Thread.Sleep(2000);

			Assert.AreEqual("T1T2", result.ToString());

			sched.Shutdown();
		}
        public void TestNoConcurrentExecOnSameJobWithBatching()
        {
            DateTime startTime = DateTime.Now.AddMilliseconds(300).ToUniversalTime(); // make the triggers fire at the same time.

            IJobDetail job1 = JobBuilder.Create<TestJob>().WithIdentity("job1").Build();
            ITrigger trigger1 = TriggerBuilder.Create().WithSimpleSchedule().StartAt(startTime).Build();

            ITrigger trigger2 = TriggerBuilder.Create().WithSimpleSchedule().StartAt(startTime).ForJob(job1).Build();

            NameValueCollection props = new NameValueCollection();
            props["quartz.scheduler.idleWaitTime"] = "1500";
            props["quartz.scheduler.batchTriggerAcquisitionMaxCount"] = "2";
            props["quartz.threadPool.threadCount"] = "2";
            IScheduler scheduler = new StdSchedulerFactory(props).GetScheduler();
            scheduler.ListenerManager.AddJobListener(new TestJobListener(2));
            scheduler.ScheduleJob(job1, trigger1);
            scheduler.ScheduleJob(trigger2);

            scheduler.Start();
            barrier.WaitOne();
            scheduler.Shutdown(true);

            Assert.AreEqual(2, jobExecDates.Count);
            Assert.Greater(jobExecDates[1] - jobExecDates[0], jobBlockTime);
        }
Пример #3
0
        public override bool OnStart()
        {
            Trace.WriteLine("WorkerRole1 Run", "Information");

            var properties = new NameValueCollection();
            properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.dataSource"] = "default";
            properties["quartz.jobStore.clustered"] = "true";
            properties["quartz.jobStore.selectWithLockSQL"] = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}{1} WHERE {2} = {3} AND {4} = @lockName", new object[] { "{0}", "LOCKS", "SCHED_NAME", "{1}", "LOCK_NAME" });
            properties["quartz.jobStore.acquireTriggersWithinLock"] = "true";
            properties["quartz.scheduler.instanceId"] = "AUTO";
            properties["quartz.threadPool.threadCount"] = "1";
            properties["quartz.jobStore.tablePrefix"] = "Scheduling.";
            properties["quartz.dataSource.default.connectionString"] = @"Server = (local)\sqlexpress; Database = DB; Integrated Security = True";
            properties["quartz.dataSource.default.provider"] = "SqlServer-20";

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

            var triggerKey = new TriggerKey("t1");
            var trigger = scheduler.GetTrigger(triggerKey);

            var jobBuilder = JobBuilder.Create<Job>();
            var job = jobBuilder.Build();

            var t = scheduler.GetTrigger(new TriggerKey("t1"));

            trigger = new SimpleTriggerImpl("t1", 100000, TimeSpan.FromSeconds(5));

            scheduler.ScheduleJob(job, trigger);

            scheduler.Start();

            return base.OnStart();
        }
        public void TestTriggerFinalized()
        {
            Qtz205TriggerListener triggerListener = new Qtz205TriggerListener();
            Qtz205ScheListener schedulerListener = new Qtz205ScheListener();
            NameValueCollection props = new NameValueCollection();
            props["quartz.scheduler.idleWaitTime"] = "1500";
            props["quartz.threadPool.threadCount"] = "2";
            IScheduler scheduler = new StdSchedulerFactory(props).GetScheduler();
            scheduler.ListenerManager.AddSchedulerListener(schedulerListener);
            scheduler.ListenerManager.AddTriggerListener(triggerListener);

            IJobDetail job = JobBuilder.Create<Qtz205Job>().WithIdentity("test").Build();
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("test")
                .WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForTotalCount(3))
                .Build();

            scheduler.ScheduleJob(job, trigger);
            scheduler.Start();
            Thread.Sleep(5000);

            scheduler.Shutdown(true);

            Assert.AreEqual(2, jobExecutionCount);
            Assert.AreEqual(3, triggerListener.FireCount);
            Assert.AreEqual(1, schedulerListener.TriggerFinalizedCount);
        }
Пример #5
0
        static void Main(string[] args)
        {
            var scheduler = new StdSchedulerFactory().GetScheduler();

            // add scheduler listener
            scheduler.ListenerManager.AddSchedulerListener(new SchedulerListener());

            // add global job listener
            scheduler.ListenerManager.AddJobListener(new JobListener(), GroupMatcher<JobKey>.AnyGroup());

            // add global trigger listener
            scheduler.ListenerManager.AddTriggerListener(new TriggerListener(), GroupMatcher<TriggerKey>.AnyGroup());

            // add jobs & triggers
            scheduler.ScheduleJob(
                JobBuilder.Create<ExampleJob>().WithIdentity("MyJob", "MyJobGroup").Build(),
                TriggerBuilder.Create().WithIdentity("MyTrigger", "MyTriggerGroup")
                    .WithSimpleSchedule(s => s.WithIntervalInSeconds(2).RepeatForever()).Build());

            scheduler.Start(); // start scheduler
            Thread.Sleep(5000); // sleep the main thread (Quartz will fire the job 3x on other threads)
            scheduler.Shutdown(true); // stop the scheduler

            Console.ReadLine();
        }
Пример #6
0
        static void Main(string[] args)
        {
            var settings = SettingsFactory.Create<PingerSettings>(ConfigurationManager.AppSettings["settings"]);

            if(settings != null && settings.Pings != null && settings.Pings.Count > 0)
            {
                // construct a scheduler
                var scheduler = new StdSchedulerFactory().GetScheduler();
                scheduler.Start();

                settings.Pings.ForEach(p=>
                {
                    var job = JobBuilder.Create<Pinger>()
                        .UsingJobData("urls",string.Join(",",p.Urls))
                        .Build();

                    var trigger = TriggerBuilder.Create()
                                    .WithSimpleSchedule(x =>
                                    x.WithInterval(TimeSpan.FromMinutes(p.Interval)).RepeatForever())
                                    .Build();

                    scheduler.ScheduleJob(job, trigger);
                });
            }
        }
        public void TestJobInterruption()
        {
            // create a simple scheduler

            NameValueCollection config = new NameValueCollection();
            config["quartz.scheduler.instanceName"] = "InterruptableJobTest_Scheduler";
            config["quartz.scheduler.instanceId"] = "AUTO";
            config["quartz.threadPool.threadCount"] = "2";
            config["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool";
            IScheduler sched = new StdSchedulerFactory(config).GetScheduler();
            sched.Start();

            // add a job with a trigger that will fire immediately

            IJobDetail job = JobBuilder.Create<TestInterruptableJob>()
                .WithIdentity("j1")
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("t1")
                .ForJob(job)
                .StartNow()
                .Build();

            sched.ScheduleJob(job, trigger);

            sync.WaitOne(); // make sure the job starts running...

            IList<IJobExecutionContext> executingJobs = sched.GetCurrentlyExecutingJobs();

            Assert.AreEqual(1, executingJobs.Count, "Number of executing jobs should be 1 ");

            IJobExecutionContext jec = executingJobs[0];

            bool interruptResult = sched.Interrupt(jec.FireInstanceId);

            sync.WaitOne(); // wait for the job to terminate

            Assert.IsTrue(interruptResult, "Expected successful result from interruption of job ");
            Assert.IsTrue(TestInterruptableJob.interrupted, "Expected interrupted flag to be set on job class ");

            sched.Clear();
            sched.Shutdown();
        }
Пример #8
0
        static void Main(string[] args)
        {
            var properties = new NameValueCollection();
            properties["quartz.threadPool.threadCount"] = "1";
            
            const string cronExpression = "0/30 * * * * ?";

            var scheduler = new StdSchedulerFactory(properties).GetScheduler();
            
            var job = new JobDetail("NomeJob", "GrupoJob", typeof(BillingJob));

            var trigger = new CronTrigger("NomeTrigger", "GrupoTrigger", "NomeJob", "GrupoJob", cronExpression);

            scheduler.ScheduleJob(job, trigger);

            scheduler.Start();

            Console.ReadKey();

            scheduler.Shutdown();
        }
Пример #9
0
        static void Main(string[] args)
        {
            //ScheduledJob.Run();
            // TODO: Initialiaze Scheduler
            var scheduler = new StdSchedulerFactory().GetScheduler();
            scheduler.Start();

            var jobDetail = JobBuilder.Create<ExampleJob>()
                .WithIdentity(new JobKey("ExampleJob"))
                .Build();
            jobDetail.JobDataMap.Put("DataKey", "Passed value");
            jobDetail.JobDataMap.Put("FilePath", ConfigurationManager.AppSettings["FilePath"] as string);

            // Let's create a trigger that fires immediately
            ICronTrigger trigger = TriggerBuilder.Create()
                                                 .WithIdentity("WriteHelloToLog", "IT")
                                                 .WithCronSchedule("0 0/1 * 1/1 * ? *") //-> visit http://www.cronmaker.com/ Queues the job every minute
                                                 .StartAt(DateTime.UtcNow)
                                                 .WithPriority(1)
                                                 .Build() as ICronTrigger;

            ITrigger dailyTrigger = TriggerBuilder.Create()
                                      .WithDailyTimeIntervalSchedule(schedBuilder => schedBuilder
                                          .WithIntervalInMinutes(30)
                                          .OnDaysOfTheWeek(new[] {
                                                          DayOfWeek.Monday,
                                                          DayOfWeek.Tuesday,
                                                          DayOfWeek.Wednesday,
                                                          DayOfWeek.Thursday,
                                                          DayOfWeek.Friday })
                                          .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(9, 30))
                                          .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(19, 30)))
                                      .Build();

            scheduler.ScheduleJob(jobDetail, trigger);

            scheduler.TriggerJob(new JobKey("ExampleJob"));
        }
        private void StartCronJobs()
        {
            IScheduler sched;
            IJobDetail jobDetail;
            ITrigger trigger;

            var cronJobs = new r3mus_DBEntities().CRONJobs; //.Where(cronJob => cronJob.Enabled == true);

            cronJobs.ToList().ForEach(cronJob =>
            {
                sched = new StdSchedulerFactory().GetScheduler();
                sched.Start();

                jobDetail = JobBuilder.Create(Type.GetType(string.Concat("r3mus.CRONJobs.", cronJob.JobName)))
                    .WithIdentity(string.Format("{0}Instance", cronJob.JobName), string.Format("{0}Group", cronJob.JobName))
                    .Build();
                trigger = TriggerBuilder.Create()
                    .WithIdentity(string.Format("{0}Trigger", cronJob.JobName), string.Format("{0}TriggerGroup", cronJob.JobName))
                    .StartNow()
                    .WithSimpleSchedule(x => x.WithIntervalInMinutes(cronJob.Schedule).RepeatForever())
                    .Build();
                sched.ScheduleJob(jobDetail, trigger);
            });

            sched = new StdSchedulerFactory().GetScheduler();
            sched.Start();

            //jobDetail = JobBuilder.Create(Type.GetType("r3mus.CRONJobs.PreloadInfo"))
            //    .WithIdentity("PreloadInfoInstance", "PreloadInfoGroup")
            //    .Build();
            //trigger = TriggerBuilder.Create()
            //    .WithIdentity("PreloadInfoTrigger", "PreloadInfoTriggerGroup")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x.WithIntervalInMinutes(15).RepeatForever())
            //    .Build();
            //sched.ScheduleJob(jobDetail, trigger);
        }
Пример #11
0
        protected override void OnStart(string[] args)
        {
            //ScheduledJob.Run();
            // TODO Initialiaze Scheduler
            var scheduler = new StdSchedulerFactory().GetScheduler();
            scheduler.Start();

            var jobDetail = JobBuilder.Create<HelloWorldJob>()
                .WithIdentity(new JobKey("HelloWorldJob"))
                .Build();
            jobDetail.JobDataMap.Put("DataKey", "Passed value");
            jobDetail.JobDataMap.Put("FilePath", System.Configuration.ConfigurationManager.AppSettings["FilePath"] as string);

            // Let's create a trigger that fires immediately
            var trigger = (ICronTrigger)TriggerBuilder.Create()
                .WithIdentity("WriteHelloToLog", "IT")
                .WithCronSchedule("0 0/1 * 1/1 * ? *") // visit http://www.cronmaker.com/ Queues the job every minute
                .StartAt(DateTime.UtcNow)
                .WithPriority(1)
                .Build();
            scheduler.ScheduleJob(jobDetail, trigger);

            scheduler.TriggerJob(new JobKey("HelloWorldJob"));
        }
Пример #12
0
        static IScheduler SetupScheduler()
        {
            var scheduler = new StdSchedulerFactory().GetScheduler();
            scheduler.Start();
            var job = JobBuilder.Create<IndexAgent>().WithIdentity("Indexer").Build();
            var trigger = TriggerBuilder.Create()
                .StartNow()
                .WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
//                .WithSimpleSchedule(x => x.WithIntervalInMinutes(30).RepeatForever())
//                .WithSimpleSchedule(x => x.WithIntervalInSeconds(30).RepeatForever())
                .Build();
            scheduler.ScheduleJob(job, trigger);
            return scheduler;
        }
Пример #13
0
        public void TestBasicStorageFunctions()
        {
            NameValueCollection config = new NameValueCollection();
            config["quartz.scheduler.instanceName"] = "SchedulerTest_Scheduler";
            config["quartz.scheduler.instanceId"] = "AUTO";
            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.Create()
                                       .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()
                                             .WithSimpleSchedule(x => x.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.Create()
                            .OfType<TestJob>()
                            .WithIdentity("j2", "g1")
                            .Build();

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

            sched.ScheduleJob(job, trigger);

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

            trigger = TriggerBuilder.Create()
                                    .WithIdentity("t3", "g1")
                                    .ForJob(job)
                                    .StartNow()
                                    .WithSimpleSchedule(x => x.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.Create()
                            .OfType<TestJob>()
                            .WithIdentity("j4", "g1")
                            .Build();

            trigger = TriggerBuilder.Create()
                                    .WithIdentity("t4", "g1")
                                    .ForJob(job)
                                    .StartNow()
                                    .WithSimpleSchedule(x => x.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 ");

            sched.Shutdown();
        }
Пример #14
0
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {
                var jobService = new ServiceJobService( rockContext );

                ServiceJob job = jobService.Get( JobId );
                if ( job != null )
                {
                    try
                    {
                        // create a scheduler specific for the job
                        var scheduleConfig = new System.Collections.Specialized.NameValueCollection();
                        var runNowSchedulerName = ( "RunNow:" + job.Guid.ToString( "N" ) ).Truncate( 40 );
                        scheduleConfig.Add( StdSchedulerFactory.PropertySchedulerInstanceName, runNowSchedulerName );
                        var schedulerFactory = new StdSchedulerFactory( scheduleConfig );
                        var sched = new StdSchedulerFactory( scheduleConfig ).GetScheduler();
                        if (sched.IsStarted)
                        {
                            // the job is currently running as a RunNow job
                            return;
                        }

                        // create the quartz job and trigger
                        IJobDetail jobDetail = jobService.BuildQuartzJob( job );
                        var jobTrigger = TriggerBuilder.Create()
                            .WithIdentity( job.Guid.ToString(), job.Name )
                            .StartNow()
                            .Build();

                        // schedule the job
                        sched.ScheduleJob( jobDetail, jobTrigger );

                        // set up the listener to report back from the job when it completes
                        sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() );

                        // start the scheduler
                        sched.Start();

                        // Wait 10secs to give job chance to start
                        Thread.Sleep( new TimeSpan( 0, 0, 10 ) );

                        // stop the scheduler when done with job
                        sched.Shutdown( true );
                    }

                    catch ( Exception ex )
                    {
                        // create a friendly error message
                        ExceptionLogService.LogException( ex, null );
                        string message = string.Format( "Error doing a 'Run Now' on job: {0}. \n\n{2}", job.Name, job.Assembly, ex.Message );
                        job.LastStatusMessage = message;
                        job.LastStatus = "Error Loading Job";
                        rockContext.SaveChanges();
                    }
                }
            }
        }
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using ( var rockContext = new RockContext() )
            {
                var jobService = new ServiceJobService( rockContext );

                ServiceJob job = jobService.Get( JobId );
                if ( job != null )
                {
                    try
                    {
                        // create a scheduler
                        var scheduleConfig = new System.Collections.Specialized.NameValueCollection();
                        scheduleConfig.Add( "org.quartz.scheduler.instanceName", "RunNow" );
                        var sched = new StdSchedulerFactory( scheduleConfig ).GetScheduler();

                        // create the quartz job and trigger
                        IJobDetail jobDetail = jobService.BuildQuartzJob( job );
                        var jobTrigger = TriggerBuilder.Create()
                            .WithIdentity( job.Guid.ToString(), job.Name )
                            .StartNow()
                            .Build();

                        // schedule the job
                        sched.ScheduleJob( jobDetail, jobTrigger );

                        // set up the listener to report back from the job when it completes
                        sched.ListenerManager.AddJobListener( new RockJobListener(), EverythingMatcher<JobKey>.AllJobs() );

                        // start the scheduler
                        sched.Start();

                        // Wait 10secs to give job chance to start
                        Thread.Sleep( new TimeSpan( 0, 0, 10 ) );

                        // stop the scheduler when done with job
                        sched.Shutdown( true );
                    }

                    catch ( Exception ex )
                    {
                        // create a friendly error message
                        string message = string.Format( "Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message );
                        job.LastStatusMessage = message;
                        job.LastStatus = "Error Loading Job";
                        rockContext.SaveChanges();
                    }
                }
            }
        }