Beispiel #1
0
        public virtual void JobWasExecuted(IJobExecutionContext inContext, JobExecutionException inException)
        {
            log.Info("Job1Listener says: Job was executed.");

            // Simple job #2
            IJobDetail job2 = JobBuilder.NewJob <SimpleJob2>()
                              .WithIdentity("job2")
                              .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("job2Trigger")
                               .StartNow()
                               .Build();

            try
            {
                // schedule the job to run!
                inContext.Scheduler.ScheduleJob(job2, trigger);
            }
            catch (SchedulerException e)
            {
                log.Warn("Unable to schedule job2!");
                Console.Error.WriteLine(e.StackTrace);
            }
        }
Beispiel #2
0
        public JobBuilder GetJobBuilder()
        {
            JobBuilder b = JobBuilder.NewJob()
                           .OfType(JobType)
                           .RequestRecovery(RequestsRecovery)
                           .StoreDurably(Durable)
                           .UsingJobData(JobDataMap)
                           .WithDescription(description)
                           .WithIdentity(Key);

            return(b);
        }
Beispiel #3
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(SimpleExample));

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

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

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


            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

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

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

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .StartAt(runTime)
                               .Build();

            // Tell quartz to schedule the job using our trigger
            sched.ScheduleJob(job, trigger);
            log.Info(string.Format("{0} will run at: {1}", job.Key, runTime.ToString("r")));

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

            // wait long enough so that the scheduler as an opportunity to
            // run the job!
            log.Info("------- Waiting 65 seconds... -------------");

            // wait 65 seconds to show jobs
            Thread.Sleep(TimeSpan.FromSeconds(65));

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");
        }
Beispiel #4
0
        public void TestJobBuilder()
        {
            IJobDetail job = JobBuilder.NewJob()
                             .OfType <TestJob>()
                             .WithIdentity("j1")
                             .StoreDurably()
                             .Build();

            Assert.AreEqual("j1", job.Key.Name, "Unexpected job name: " + job.Key.Name);
            Assert.IsTrue(job.Key.Group.Equals(JobKey.DefaultGroup), "Unexpected job group: " + job.Key.Group);
            Assert.IsTrue(job.Key.Equals(new JobKey("j1")), "Unexpected job key: " + job.Key);
            Assert.IsTrue(job.Description == null, "Unexpected job description: " + job.Description);
            Assert.IsTrue(job.Durable, "Expected isDurable == true ");
            Assert.IsFalse(job.RequestsRecovery, "Expected requestsRecovery == false ");
            Assert.IsFalse(job.ConcurrentExectionDisallowed, "Expected isConcurrentExectionDisallowed == false ");
            Assert.IsFalse(job.PersistJobDataAfterExecution, "Expected isPersistJobDataAfterExecution == false ");
            Assert.IsTrue(job.JobType.Equals(typeof(TestJob)), "Unexpected job class: " + job.JobType)
            ;

            job = JobBuilder.NewJob()
                  .OfType <TestAnnotatedJob>()
                  .WithIdentity("j1")
                  .WithDescription("my description")
                  .StoreDurably(true)
                  .RequestRecovery()
                  .Build();

            Assert.IsTrue(job.Description.Equals("my description"), "Unexpected job description: " + job.Description);
            Assert.IsTrue(job.Durable, "Expected isDurable == true ");
            Assert.IsTrue(job.RequestsRecovery, "Expected requestsRecovery == true ");
            Assert.IsTrue(job.ConcurrentExectionDisallowed, "Expected isConcurrentExectionDisallowed == true ");
            Assert.IsTrue(job.PersistJobDataAfterExecution, "Expected isPersistJobDataAfterExecution == true ");

            job = JobBuilder.NewJob()
                  .OfType <TestStatefulJob>()
                  .
                  WithIdentity("j1", "g1")
                  .RequestRecovery(false)
                  .Build();

            Assert.IsTrue(job.Key.Group.Equals("g1"), "Unexpected job group: " + job.Key.Name);
            Assert.IsFalse(job.Durable, "Expected isDurable == false ");
            Assert.IsFalse(job.RequestsRecovery, "Expected requestsRecovery == false ");
            Assert.IsTrue(job.ConcurrentExectionDisallowed, "Expected isConcurrentExectionDisallowed == true ");
            Assert.IsTrue(job.PersistJobDataAfterExecution, "Expected isPersistJobDataAfterExecution == true ");
        }
Beispiel #5
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(RemoteClientExample));

            NameValueCollection properties = new NameValueCollection();

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

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

            // set remoting expoter
            properties["quartz.scheduler.proxy"]         = "true";
            properties["quartz.scheduler.proxy.address"] = "tcp://127.0.0.1:555/QuartzScheduler";

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

            // define the job and ask it to run

            IJobDetail job = JobBuilder.NewJob <SimpleJob>()
                             .WithIdentity("remotelyAddedJob", "default")
                             .Build();

            JobDataMap map = job.JobDataMap;

            map.Put("msg", "Your remotely added job has executed!");

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("remotelyAddedTrigger", "default")
                               .ForJob(job.Key)
                               .WithSchedule(CronScheduleBuilder.CronSchedule("/5 * * ? * *"))
                               .Build();

            // schedule the job
            sched.ScheduleJob(job, trigger);

            log.Info("Remote job scheduled.");
        }
Beispiel #6
0
        public void TestTriggerBuilder()
        {
            IJobDetail job = JobBuilder.NewJob()
                             .OfType <TestJob>()
                             .WithIdentity("j1")
                             .StoreDurably()
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .Build();

            Assert.IsTrue(trigger.Key.Name != null, "Expected non-null trigger name ");
            Assert.IsTrue(trigger.Key.Group.Equals(JobKey.DefaultGroup), "Unexpected trigger group: " + trigger.Key.Group);
            Assert.IsTrue(trigger.JobKey == null, "Unexpected job key: " + trigger.JobKey);
            Assert.IsTrue(trigger.Description == null, "Unexpected job description: " + trigger.Description);
            Assert.IsTrue(trigger.Priority == TriggerConstants.DefaultPriority, "Unexpected trigger priority: " + trigger.Priority);
            Assert.IsTrue(trigger.StartTimeUtc != null, "Unexpected start-time: " + trigger.StartTimeUtc);
            Assert.IsTrue(trigger.EndTimeUtc == null, "Unexpected end-time: " + trigger.EndTimeUtc);

            DateTimeOffset stime = DateBuilder.EvenSecondDateAfterNow();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t1")
                      .WithDescription("my description")
                      .WithPriority(2)
                      .EndAt(DateBuilder.FutureDate(10, DateBuilder.IntervalUnit.Week))
                      .StartAt(stime)
                      .Build();

            Assert.IsTrue(trigger.Key.Name.Equals("t1"), "Unexpected trigger name " + trigger.Key.Name);
            Assert.IsTrue(trigger.Key.Group.Equals(JobKey.DefaultGroup), "Unexpected trigger group: " + trigger.Key.Group);
            Assert.IsTrue(trigger.JobKey == null, "Unexpected job key: " + trigger.JobKey);
            Assert.IsTrue(trigger.Description.Equals("my description"), "Unexpected job description: " + trigger.Description);
            Assert.IsTrue(trigger.Priority == 2, "Unexpected trigger priortiy: " + trigger);
            Assert.IsTrue(trigger.StartTimeUtc.Equals(stime), "Unexpected start-time: " + trigger.StartTimeUtc);
            Assert.IsTrue(trigger.EndTimeUtc != null, "Unexpected end-time: " + trigger.EndTimeUtc);
        }
Beispiel #7
0
        public void ExceptionPolicyRestartImmediately()
        {
            sched.Start();
            JobKey     jobKey       = new JobKey("ExceptionPolicyRestartJob", "ExceptionPolicyRestartGroup");
            IJobDetail exceptionJob = JobBuilder.NewJob <ExceptionJob>()
                                      .WithIdentity(jobKey)
                                      .StoreDurably()
                                      .Build();

            sched.AddJob(exceptionJob, false);

            ExceptionJob.ThrowsException         = true;
            ExceptionJob.Refire                  = true;
            ExceptionJob.UnscheduleAllTriggers   = false;
            ExceptionJob.UnscheduleFiringTrigger = false;
            ExceptionJob.LaunchCount             = 0;
            sched.TriggerJob(jobKey);

            int i = 10;

            while ((i > 0) && (ExceptionJob.LaunchCount <= 1))
            {
                i--;
                Thread.Sleep(200);
                if (ExceptionJob.LaunchCount > 1)
                {
                    break;
                }
            }
            // to ensure job will not be refired in consequent tests
            // in fact, it would be better to have a separate class
            ExceptionJob.ThrowsException = false;
            sched.DeleteJob(jobKey);
            Thread.Sleep(1000);
            Assert.Greater(ExceptionJob.LaunchCount, 1, "The job should have been refired after exception");
        }
Beispiel #8
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 ----------------");
        }
Beispiel #9
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(CronTriggerExample));

            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 sched.start() has been called

            // job 1 will run every 20 seconds

            IJobDetail job = JobBuilder.NewJob <SimpleJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                   .WithIdentity("trigger1", "group1")
                                   .WithSchedule(CronScheduleBuilder.CronSchedule("0/20 * * * * ?"))
                                   .Build();

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

            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 2 will run every other minute (at 15 seconds past the minute)
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job2", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger2", "group1")
                      .WithSchedule(CronScheduleBuilder.CronSchedule("15 0/2 * * * ?"))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 3 will run every other minute but only between 8am and 5pm
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job3", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger3", "group1")
                      .WithSchedule(CronScheduleBuilder.CronSchedule("0 0/2 8-17 * * ?"))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 4 will run every three minutes but only between 5pm and 11pm
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job4", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger4", "group1")
                      .WithSchedule(CronScheduleBuilder.CronSchedule("0 0/3 17-23 * * ?"))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 5 will run at 10am on the 1st and 15th days of the month
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job5", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger5", "group1")
                      .WithSchedule(CronScheduleBuilder.CronSchedule("0 0 10am 1,15 * ?"))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 6 will run every 30 seconds but only on Weekdays (Monday through Friday)
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job6", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger6", "group1")
                      .WithSchedule(CronScheduleBuilder.CronSchedule("0,30 * * ? * MON-FRI"))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 7 will run every 30 seconds but only on Weekends (Saturday and Sunday)
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job7", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger7", "group1")
                      .WithSchedule(CronScheduleBuilder.CronSchedule("0,30 * * ? * SAT,SUN"))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

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

            // All of the jobs have been added to the scheduler, but none of the
            // jobs
            // will run until the scheduler has been started
            sched.Start();

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

            log.Info("------- Waiting five minutes... ------------");
            try
            {
                // wait five minutes to show jobs
                Thread.Sleep(300 * 1000);
                // executing...
            }
            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));
        }
Beispiel #10
0
        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));
                        }
                    }
                }
            }

            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 'ignore-duplicates' 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 'overwrite-existing-data' not specified, defaulting to " + IgnoreDuplicates);
            }

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

            if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].job != null)
            {
                jobNodes.AddRange(data.schedule[0].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.NewJob(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 && data.schedule.Length > 0 && data.schedule[0].trigger != null)
            {
                triggerEntries.AddRange(data.schedule[0].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 triggerMisfireInstructionConst;
                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;

                TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);

                IScheduleBuilder sched = null;

                if (triggerNode.Item is simpleTriggerType)
                {
                    simpleTriggerType simpleTrigger = (simpleTriggerType)triggerNode.Item;
                    triggerMisfireInstructionConst = simpleTrigger.misfireinstruction;
                    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;
                    triggerMisfireInstructionConst = cronTrigger.misfireinstruction;
                    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();

                    triggerMisfireInstructionConst = calendarIntervalTrigger.misfireinstruction;
                    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);
            }
        }
Beispiel #11
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));
        }
Beispiel #12
0
        public void Run()
        {
            ILog log = LogManager.GetLogger(typeof(PriorityExample));

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

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

            properties["quartz.scheduler.instanceName"] = "PriorityExampleScheduler";
            // Set thread count to 1 to force Triggers scheduled for the same time to
            // to be ordered by priority.
            properties["quartz.threadPool.threadCount"] = "1";
            properties["quartz.threadPool.type"]        = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.jobStore.type"]          = "Quartz.Simpl.RAMJobStore, Quartz";
            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = sf.GetScheduler();

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

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

            IJobDetail job = JobBuilder.NewJob <TriggerEchoJob>()
                             .WithIdentity("TriggerEchoJob")
                             .Build();

            // All three triggers will fire their first time at the same time,
            // ordered by their priority, and then repeat once, firing in a
            // staggered order that therefore ignores priority.
            //
            // We should see the following firing order:
            // 1. Priority10Trigger15SecondRepeat
            // 2. Priority5Trigger10SecondRepeat
            // 3. PriorityNeg5Trigger5SecondRepeat
            // 4. PriorityNeg5Trigger5SecondRepeat
            // 5. Priority5Trigger10SecondRepeat
            // 6. Priority10Trigger15SecondRepeat

            // Calculate the start time of all triggers as 5 seconds from now
            DateTimeOffset startTime = DateBuilder.FutureDate(5, DateBuilder.IntervalUnit.Second);

            // First trigger has priority of 1, and will repeat after 5 seconds
            ITrigger trigger1 = TriggerBuilder.Create()
                                .WithIdentity("PriorityNeg5Trigger5SecondRepeat")
                                .StartAt(startTime)
                                .WithSchedule(SimpleScheduleBuilder.Create().WithRepeatCount(1).WithIntervalInSeconds(5))
                                .WithPriority(1)
                                .ForJob(job)
                                .Build();

            // Second trigger has default priority of 5 (default), and will repeat after 10 seconds
            ITrigger trigger2 = TriggerBuilder.Create()
                                .WithIdentity("Priority5Trigger10SecondRepeat")
                                .StartAt(startTime)
                                .WithSchedule(SimpleScheduleBuilder.Create().WithRepeatCount(1).WithIntervalInSeconds(10))
                                .ForJob(job)
                                .Build();

            // Third trigger has priority 10, and will repeat after 15 seconds
            ITrigger trigger3 = TriggerBuilder.Create()
                                .WithIdentity("Priority10Trigger15SecondRepeat")
                                .StartAt(startTime)
                                .WithSchedule(SimpleScheduleBuilder.Create().WithRepeatCount(1).WithIntervalInSeconds(15))
                                .WithPriority(10)
                                .ForJob(job)
                                .Build();

            // Tell quartz to schedule the job using our trigger
            sched.ScheduleJob(job, trigger1);
            sched.ScheduleJob(trigger2);
            sched.ScheduleJob(trigger3);

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

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

            try
            {
                Thread.Sleep(TimeSpan.FromSeconds(30));
            }
            catch (ThreadInterruptedException)
            {
            }

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");
        }
Beispiel #13
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(CalendarExample));

            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 -------------------");

            // Add the holiday calendar to the schedule
            AnnualCalendar holidays = new AnnualCalendar();

            // fourth of July (July 4)
            DateTime fourthOfJuly = new DateTime(DateTime.UtcNow.Year, 7, 4);

            holidays.SetDayExcluded(fourthOfJuly, true);

            // halloween (Oct 31)
            DateTime halloween = new DateTime(DateTime.UtcNow.Year, 10, 31);

            holidays.SetDayExcluded(halloween, true);

            // christmas (Dec 25)
            DateTime christmas = new DateTime(DateTime.UtcNow.Year, 12, 25);

            holidays.SetDayExcluded(christmas, true);

            // tell the schedule about our holiday calendar
            sched.AddCalendar("holidays", holidays, false, false);


            // schedule a job to run hourly, starting on halloween
            // at 10 am

            DateTimeOffset runDate = DateBuilder.DateOf(0, 0, 10, 31, 10);

            IJobDetail job = JobBuilder.NewJob <SimpleJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(runDate)
                                     .WithSchedule(SimpleScheduleBuilder.Create()
                                                   .WithIntervalInHours(1)
                                                   .RepeatForever())
                                     .ModifiedByCalendar("holidays")
                                     .Build();

            // schedule the job and print the first run date
            DateTimeOffset firstRunTime = sched.ScheduleJob(job, trigger);

            // print out the first execution date.
            // Note:  Since Halloween (Oct 31) is a holiday, then
            // we will not run unti the next day! (Nov 1)
            log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, firstRunTime.ToString("r"), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            log.Info("------- Starting Scheduler ----------------");
            sched.Start();

            // wait 30 seconds:
            // note:  nothing will run
            log.Info("------- Waiting 30 seconds... --------------");
            try
            {
                // wait 30 seconds to show jobs
                Thread.Sleep(30 * 1000);
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }


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

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Beispiel #14
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(JobStateExample));

            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 ----------------");

            // get a "nice round" time a few seconds in the future....
            DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 10);

            // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds
            IJobDetail job1 = JobBuilder.NewJob <ColorJob>()
                              .WithIdentity("job1", "group1")
                              .Build();

            ISimpleTrigger trigger1 = (ISimpleTrigger)TriggerBuilder.Create()
                                      .WithIdentity("trigger1", "group1")
                                      .StartAt(startTime)
                                      .WithSchedule(SimpleScheduleBuilder.Create()
                                                    .WithIntervalInSeconds(10)
                                                    .WithRepeatCount(4))
                                      .Build();

            // pass initialization parameters into the job
            job1.JobDataMap.Put(ColorJob.FavoriteColor, "Green");
            job1.JobDataMap.Put(ColorJob.ExecutionCount, 1);

            // schedule the job to run
            DateTimeOffset scheduleTime1 = sched.ScheduleJob(job1, trigger1);

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

            // job2 will also run 5 times, every 10 seconds

            IJobDetail job2 = JobBuilder.NewJob <ColorJob>()
                              .WithIdentity("job2", "group1")
                              .Build();

            ISimpleTrigger trigger2 = (ISimpleTrigger)TriggerBuilder.Create()
                                      .WithIdentity("trigger2", "group1")
                                      .StartAt(startTime)
                                      .WithSchedule(SimpleScheduleBuilder.Create()
                                                    .WithIntervalInSeconds(10)
                                                    .WithRepeatCount(4))
                                      .Build();

            // pass initialization parameters into the job
            // this job has a different favorite color!
            job2.JobDataMap.Put(ColorJob.FavoriteColor, "Red");
            job2.JobDataMap.Put(ColorJob.ExecutionCount, 1);

            // schedule the job to run
            DateTimeOffset scheduleTime2 = sched.ScheduleJob(job2, trigger2);

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


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

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            sched.Start();

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

            log.Info("------- Waiting 60 seconds... -------------");
            try
            {
                // wait five minutes to show jobs
                Thread.Sleep(300 * 1000);
                // executing...
            }
            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));
        }
Beispiel #15
0
        public virtual void Run()
        {
            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 -------------------");

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

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

            IJobDetail job = JobBuilder.NewJob <DumbInterruptableJob>()
                             .WithIdentity("interruptableJob1", "group1")
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(startTime)
                                     .WithSchedule(SimpleScheduleBuilder.Create()
                                                   .WithIntervalInSeconds(5)
                                                   .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));

            // start up the scheduler (jobs do not start to fire until
            // the scheduler has been started)
            sched.Start();
            log.Info("------- Started Scheduler -----------------");


            log.Info("------- Starting loop to interrupt job every 7 seconds ----------");
            for (int i = 0; i < 50; i++)
            {
                try
                {
                    Thread.Sleep(TimeSpan.FromSeconds(7));
                    // tell the scheduler to interrupt our job
                    sched.Interrupt(job.Key);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

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

            sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");
            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Beispiel #16
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(JobExceptionExample));

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

            // badJob1 will run every three seconds
            // this job will throw an exception and refire
            // immediately
            IJobDetail job = JobBuilder.NewJob <BadJob1>()
                             .WithIdentity("badJob1", "group1")
                             .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(job.Key + " will run at: " + ft + " and repeat: "
                     + trigger.RepeatCount + " times, every "
                     + trigger.RepeatInterval.TotalSeconds + " seconds");

            // badJob2 will run every three seconds
            // this job will throw an exception and never
            // refire
            job = JobBuilder.NewJob <BadJob2>()
                  .WithIdentity("badJob2", "group1")
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger2", "group1")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInSeconds(3)
                                    .RepeatForever())
                      .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 -----------------");

            // sleep for 60 seconds
            try
            {
                Thread.Sleep(TimeSpan.FromSeconds(60));
            }
            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));
        }
Beispiel #17
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(SimpleTriggerExample));

            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 sched.start() has been called

            // get a "nice round" time a few seconds in the future...
            DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15);

            // job1 will only fire once at date/time "ts"
            IJobDetail job = JobBuilder.NewJob <SimpleJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(startTime)
                                     .Build();

            // schedule it to run!
            DateTimeOffset?ft = sched.ScheduleJob(job, trigger);

            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // job2 will only fire once at date/time "ts"
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job2", "group1")
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger2", "group1")
                      .StartAt(startTime)
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // job3 will run 11 times (run once and repeat 10 more times)
            // job3 will repeat every 10 seconds
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job3", "group1")
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger3", "group1")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInSeconds(10)
                                    .WithRepeatCount(10))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // the same job (job3) will be scheduled by a another trigger
            // this time will only repeat twice at a 70 second interval

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger3", "group2")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInSeconds(10)
                                    .WithRepeatCount(2))
                      .ForJob(job)
                      .Build();

            ft = sched.ScheduleJob(trigger);
            log.Info(job.Key +
                     " will [also] run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // job4 will run 6 times (run once and repeat 5 more times)
            // job4 will repeat every 10 seconds
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job4", "group1")
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger4", "group1")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInSeconds(10)
                                    .WithRepeatCount(5))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // job5 will run once, five minutes in the future
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job5", "group1")
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger5", "group1")
                      .StartAt(DateBuilder.FutureDate(5, DateBuilder.IntervalUnit.Minute))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // job6 will run indefinitely, every 40 seconds
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job6", "group1")
                  .Build();

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

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

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

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            sched.Start();

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

            // jobs can also be scheduled after start() has been called...
            // job7 will repeat 20 times, repeat every five minutes
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job7", "group1")
                  .Build();

            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger7", "group1")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInMinutes(5)
                                    .WithRepeatCount(20))
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key +
                     " will run at: " + ft +
                     " and repeat: " + trigger.RepeatCount +
                     " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds");

            // jobs can be fired directly... (rather than waiting for a trigger)
            job = JobBuilder.NewJob <SimpleJob>()
                  .WithIdentity("job8", "group1")
                  .StoreDurably()
                  .Build();

            sched.AddJob(job, true);

            log.Info("'Manually' triggering job8...");
            sched.TriggerJob(new JobKey("job8", "group1"));

            log.Info("------- Waiting 30 seconds... --------------");

            try
            {
                // wait 30 seconds to show jobs
                Thread.Sleep(TimeSpan.FromSeconds(30));
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }

            // jobs can be re-scheduled...
            // job 7 will run immediately and repeat 10 times for every second
            log.Info("------- Rescheduling... --------------------");
            trigger = (ISimpleTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger7", "group1")
                      .StartAt(startTime)
                      .WithSchedule(SimpleScheduleBuilder.Create()
                                    .WithIntervalInMinutes(5)
                                    .WithRepeatCount(20))
                      .Build();

            ft = sched.RescheduleJob(trigger.Key, trigger);
            log.Info("job7 rescheduled to run at: " + ft);

            log.Info("------- Waiting five minutes... ------------");
            try
            {
                // wait five minutes to show jobs
                Thread.Sleep(TimeSpan.FromMinutes(5));
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }

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

            sched.Shutdown(true);

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

            // display some stats about the schedule that just ran
            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Beispiel #18
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(ListenerExample));

            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 -------------------");

            // schedule a job to run immediately
            IJobDetail job = JobBuilder.NewJob <SimpleJob1>()
                             .WithIdentity("job1")
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1")
                               .StartNow()
                               .Build();

            // Set up the listener
            IJobListener      listener = new Job1Listener();
            IMatcher <JobKey> matcher  = KeyMatcher <JobKey> .KeyEquals(job.Key);

            sched.ListenerManager.AddJobListener(listener, matcher);

            // schedule the job to run
            sched.ScheduleJob(job, trigger);

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            log.Info("------- Starting Scheduler ----------------");
            sched.Start();

            // wait 30 seconds:
            // note:  nothing will run
            log.Info("------- Waiting 30 seconds... --------------");
            try
            {
                // wait 30 seconds to show jobs
                Thread.Sleep(TimeSpan.FromSeconds(30));
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }


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

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Beispiel #19
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 ");
        }
Beispiel #20
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(LoadExample));

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

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

            log.Info("------- (Not Scheduling any Jobs - relying on XML definitions --");

            Random r = new Random();

            // schedule 500 jobs to run
            for (int count = 1; count <= numberOfJobs; count++)
            {
                IJobDetail job = JobBuilder
                                 .NewJob <SimpleJob>()
                                 .WithIdentity("job" + count, "group_1")
                                 .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                                 .Build();

                // tell the job to delay some small amount... to simulate work...
                long timeDelay = (long)(r.NextDouble() * 2500);
                job.JobDataMap.Put(SimpleJob.DelayTime, timeDelay);

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("trigger_" + count, "group_1")
                                   .StartAt(DateBuilder.FutureDate((10000 + (count * 100)), DateBuilder.IntervalUnit.Millisecond)) // space fire times a small bit
                                   .Build();

                sched.ScheduleJob(job, trigger);
                if (count % 25 == 0)
                {
                    log.Info("...scheduled " + count + " jobs");
                }
            }


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

            // start the schedule
            sched.Start();

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

            log.Info("------- Waiting five minutes... -----------");

            // wait five minutes to give our jobs a chance to run
            try
            {
                Thread.Sleep(TimeSpan.FromMinutes(5));
            }
            catch (ThreadInterruptedException)
            {
            }

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

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info("Executed " + metaData.NumberOfJobsExecuted + " jobs.");
        }