Пример #1
0
        public void TesDirectivesNoOverwriteWithIgnoreDups()
        {
            // create temp file
            string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName;

            using (TextWriter writer = new StreamWriter(tempFileName, false))
            {
                using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml")))
                {
                    writer.Write(reader.ReadToEnd());
                    writer.Flush();
                    writer.Close();
                }
            }

            IScheduler scheduler = null;

            try
            {
                StdSchedulerFactory factory = new StdSchedulerFactory();
                scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // Setup existing job with same names as in xml data.
                IJobDetail job = JobBuilder.Create <NoOpJob>()
                                 .WithIdentity("job1")
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("job1")
                                   .WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();

                scheduler.ScheduleJob(job, trigger);

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

                trigger = TriggerBuilder.Create().WithIdentity("job2").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
                scheduler.ScheduleJob(job, trigger);

                // Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true
                ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper();
                loadHelper.Initialize();
                XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(loadHelper);
                processor.ProcessFileAndScheduleJobs(tempFileName, scheduler);
                Assert.AreEqual(2, scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT")).Count);
                Assert.AreEqual(2, scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT")).Count);
            }
            finally
            {
                if (scheduler != null)
                {
                    scheduler.Shutdown();
                }
            }
        }
Пример #2
0
        public void GenericJobTypeShouldBeLoadable()
        {
            var type       = typeof(GenericJob <IJobSubType>);
            var typeString = type.AssemblyQualifiedNameWithoutVersion();
            var loadedType = new SimpleTypeLoadHelper().LoadType(typeString);

            Assert.That(typeString, Is.Not.Contains(", Version="));

            Assert.That(loadedType, Is.Not.Null);
            Assert.That(loadedType, Is.EqualTo(type));
        }
        public async Task TestAcquireTriggers()
        {
            ISchedulerSignaler schedSignaler = new SampleSignaler();
            ITypeLoadHelper    loadHelper    = new SimpleTypeLoadHelper();

            loadHelper.Initialize();

            var store = new RavenJobStore  {
                Database = "QuartzTest",
                Urls     = "[\"http://localhost:8080\"]"
            };
            await store.Initialize(loadHelper, schedSignaler);

            await store.SchedulerStarted();

            // Setup: Store jobs and triggers.
            var startTime0 = DateTime.UtcNow.AddMinutes(1).ToUniversalTime(); // a min from now.

            for (var i = 0; i < 10; i++)
            {
                var startTime = startTime0.AddMinutes(i * 1); // a min apart
                var job       = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                var schedule  = SimpleScheduleBuilder.RepeatMinutelyForever(2);
                var trigger   = (IOperableTrigger)TriggerBuilder.Create().WithIdentity("trigger" + i)
                                .WithSchedule(schedule).ForJob(job).StartAt(startTime).Build();

                // Manually trigger the first fire time computation that scheduler would do. Otherwise
                // the store.acquireNextTriggers() will not work properly.
                var fireTime = trigger.ComputeFirstFireTimeUtc(null);
                Assert.AreEqual(true, fireTime != null);

                await store.StoreJobAndTrigger(job, trigger);
            }

            // Test acquire one trigger at a time
            for (var i = 0; i < 10; i++)
            {
                DateTimeOffset noLaterThan = startTime0.AddMinutes(i);
                var            maxCount    = 1;
                var            timeWindow  = TimeSpan.Zero;
                var            triggers    = (await store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow)).ToList();
                Assert.AreEqual(1, triggers.Count);
                Assert.AreEqual("trigger" + i, triggers[0].Key.Name);

                // Let's remove the trigger now.
                await store.RemoveJob(triggers[0].JobKey);
            }
        }
Пример #4
0
        public void TestAcquireTriggers()
        {
            InitJobStore();

            ISchedulerSignaler schedSignaler = new SampleSignaler();
            ITypeLoadHelper    loadHelper    = new SimpleTypeLoadHelper();

            loadHelper.Initialize();

            var store = new RavenJobStore();

            store.Initialize(loadHelper, schedSignaler);
            store.SchedulerStarted();

            // Setup: Store jobs and triggers.
            DateTime startTime0 = DateTime.UtcNow.AddMinutes(1).ToUniversalTime(); // a min from now.

            for (int i = 0; i < 10; i++)
            {
                DateTime              startTime = startTime0.AddMinutes(i * 1); // a min apart
                IJobDetail            job       = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                SimpleScheduleBuilder schedule  = SimpleScheduleBuilder.RepeatMinutelyForever(2);
                IOperableTrigger      trigger   = (IOperableTrigger)TriggerBuilder.Create().WithIdentity("trigger" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build();

                // Manually trigger the first fire time computation that scheduler would do. Otherwise
                // the store.acquireNextTriggers() will not work properly.
                DateTimeOffset?fireTime = trigger.ComputeFirstFireTimeUtc(null);
                Assert.AreEqual(true, fireTime != null);

                store.StoreJobAndTrigger(job, trigger);
            }

            // Test acquire one trigger at a time
            for (int i = 0; i < 10; i++)
            {
                DateTimeOffset           noLaterThan = startTime0.AddMinutes(i);
                int                      maxCount    = 1;
                TimeSpan                 timeWindow  = TimeSpan.Zero;
                IList <IOperableTrigger> triggers    = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow);
                Assert.AreEqual(1, triggers.Count);
                Assert.AreEqual("trigger" + i, triggers[0].Key.Name);

                // Let's remove the trigger now.
                store.RemoveJob(triggers[0].JobKey);
            }
        }
Пример #5
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            JobDetailImpl tempJobDetail = new JobDetailImpl();

            tempJobDetail.Description = tbJobDescription.Text;
            tempJobDetail.Durable     = checkDurable.Checked;
            tempJobDetail.Group       = tbJobGroup.Text;
            ITypeLoadHelper typeLoadHelper = new SimpleTypeLoadHelper();

            typeLoadHelper.Initialize();
            tempJobDetail.JobType          = typeLoadHelper.LoadType(comboJobType.Text);
            tempJobDetail.Name             = tbJobKey.Text;
            tempJobDetail.RequestsRecovery = checkCover.Checked;
            tempJobDetail.Key = new JobKey(tbJobKey.Text, tbJobGroup.Text);
            for (int i = 0; i < tbJobData.Lines.Length; i++)
            {
                string   lineData = tbJobData.Lines[i];
                string[] dataDic  = lineData.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                if (dataDic.Length < 2)
                {
                    continue;
                }
                tempJobDetail.JobDataMap.Add(dataDic[0], dataDic[1]);
            }

            RetJobDetail = tempJobDetail;
            ITrigger tempTrigger;
            string   triggerGroup = tempJobDetail.Group;
            string   triggerName  = tempJobDetail.Name + "_Trigger";

            if (radioTriggerSimple.Checked)
            {
                TimeSpan ts = new TimeSpan(long.Parse(tbTriggerPeriod.Text) * 10000);
                tempTrigger = new SimpleTriggerImpl(triggerName, triggerGroup, -1, ts);
            }
            else
            {
                tempTrigger = new CronTriggerImpl(triggerName, triggerGroup, tbTriggerExpression.Text);
            }

            RetTrigger        = tempTrigger;
            this.DialogResult = DialogResult.OK;
        }
        public void TestAcquireTriggersInBatch()
        {
            ISchedulerSignaler schedSignaler = new SampleSignaler();
            ITypeLoadHelper    loadHelper    = new SimpleTypeLoadHelper();

            loadHelper.Initialize();

            RAMJobStore store = new RAMJobStore();

            store.Initialize(loadHelper, schedSignaler);

            // Setup: Store jobs and triggers.
            DateTimeOffset startTime0 = DateTimeOffset.UtcNow.AddMinutes(1); // a min from now.

            for (int i = 0; i < 10; i++)
            {
                DateTimeOffset        startTime = startTime0.AddMinutes(i); // a min apart
                IJobDetail            job       = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                SimpleScheduleBuilder schedule  = SimpleScheduleBuilder.RepeatMinutelyForever(2);
                IOperableTrigger      trigger   = (IOperableTrigger)TriggerBuilder.Create().WithIdentity("job" + i).WithSchedule(schedule).ForJob(job).StartAt(startTime).Build();

                // Manually trigger the first fire time computation that scheduler would do. Otherwise
                // the store.acquireNextTriggers() will not work properly.
                DateTimeOffset?fireTime = trigger.ComputeFirstFireTimeUtc(null);
                Assert.AreEqual(true, fireTime != null);

                store.StoreJobAndTrigger(job, trigger);
            }

            // Test acquire batch of triggers at a time
            DateTimeOffset           noLaterThan = startTime0.AddMinutes(10);
            int                      maxCount    = 7;
            TimeSpan                 timeWindow  = TimeSpan.FromMinutes(8);
            IList <IOperableTrigger> triggers    = store.AcquireNextTriggers(noLaterThan, maxCount, timeWindow);

            Assert.AreEqual(7, triggers.Count);
            for (int i = 0; i < 7; i++)
            {
                Assert.AreEqual("job" + i, triggers[i].Key.Name);
            }
        }
        /// <summary>
        /// Called during creation of the <see cref="IScheduler"/> in order to give
        /// the <see cref="ISchedulerPlugin"/> a chance to initialize.
        /// </summary>
        public virtual async Task Initialize(
            string pluginName,
            IScheduler scheduler,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Name           = pluginName;
            Scheduler      = scheduler;
            TypeLoadHelper = new SimpleTypeLoadHelper();
            TypeLoadHelper.Initialize();

            Log.Info("Registering Quartz Job Initialization Plug-in.");

            // Create JobFile objects
            var tokens = FileNames.Split(FileNameDelimiter).Select(x => x.TrimStart());

            foreach (string token in tokens)
            {
                JobFile jobFile = new JobFile(this, token);
                await jobFile.Initialize(cancellationToken);

                jobFiles.Add(new KeyValuePair <string, JobFile>(jobFile.FilePath, jobFile));
            }
        }
Пример #8
0
        /// <summary>
        /// Creates a scheduler using the specified thread pool and job store and
        /// binds it for remote access.
        /// </summary>
        /// <param name="schedulerName">The name for the scheduler.</param>
        /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
        /// <param name="threadPool">The thread pool for executing jobs</param>
        /// <param name="jobStore">The type of job store</param>
        /// <param name="schedulerPluginMap"></param>
        /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for
        /// the default value, which is currently 30000 ms.</param>
        /// <param name="dbFailureRetryInterval">The db failure retry interval.</param>
        public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool,
                                            IJobStore jobStore, IDictionary <string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime,
                                            TimeSpan dbFailureRetryInterval)
        {
            // Currently only one run-shell factory is available...
            IJobRunShellFactory jrsf = new StdJobRunShellFactory();

            // Fire everything up
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            threadPool.Initialize();

            QuartzSchedulerResources qrs = new QuartzSchedulerResources();

            qrs.Name       = schedulerName;
            qrs.InstanceId = schedulerInstanceId;

            SchedulerDetailsSetter.SetDetails(threadPool, schedulerName, schedulerInstanceId);

            qrs.JobRunShellFactory = jrsf;
            qrs.ThreadPool         = threadPool;
            qrs.JobStore           = jobStore;


            // add plugins
            if (schedulerPluginMap != null)
            {
                foreach (ISchedulerPlugin plugin in schedulerPluginMap.Values)
                {
                    qrs.AddSchedulerPlugin(plugin);
                }
            }

            QuartzScheduler qs = new QuartzScheduler(qrs, idleWaitTime, dbFailureRetryInterval);

            ITypeLoadHelper cch = new SimpleTypeLoadHelper();

            cch.Initialize();

            SchedulerDetailsSetter.SetDetails(jobStore, schedulerName, schedulerInstanceId);
            jobStore.Initialize(cch, qs.SchedulerSignaler);

            IScheduler scheduler = new StdScheduler(qs);

            jrsf.Initialize(scheduler);

            qs.Initialize();

            // Initialize plugins now that we have a Scheduler instance.
            if (schedulerPluginMap != null)
            {
                foreach (var pluginEntry in schedulerPluginMap)
                {
                    pluginEntry.Value.Initialize(pluginEntry.Key, scheduler);
                }
            }

            Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz scheduler '{0}", scheduler.SchedulerName));

            Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz scheduler version: {0}", qs.Version));

            SchedulerRepository schedRep = SchedulerRepository.Instance;

            qs.AddNoGCObject(schedRep);             // prevents the repository from being
            // garbage collected

            schedRep.Bind(scheduler);

            initialized = true;
        }
        public async Task TesDirectivesNoOverwriteWithIgnoreDups()
        {
            // create temp file
            string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName;

            using (TextWriter writer = new StreamWriter(File.OpenWrite(tempFileName)))
            {
                using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml")))
                {
                    await writer.WriteAsync(await reader.ReadToEndAsync());

                    await writer.FlushAsync();
                }
            }

            IScheduler scheduler = null;

            try
            {
                NameValueCollection properties = new NameValueCollection();
                properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType;

                StdSchedulerFactory factory = new StdSchedulerFactory(properties);
                scheduler = await factory.GetScheduler();

                // Setup existing job with same names as in xml data.
                IJobDetail job = JobBuilder.Create <NoOpJob>()
                                 .WithIdentity("job1")
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("job1")
                                   .WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();

                await scheduler.ScheduleJob(job, trigger);

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

                trigger = TriggerBuilder.Create().WithIdentity("job2").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
                await scheduler.ScheduleJob(job, trigger);

                // Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true
                ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper();
                loadHelper.Initialize();
                XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(loadHelper);
                await processor.ProcessFileAndScheduleJobs(tempFileName, scheduler);

                var jobKeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT"));

                Assert.AreEqual(2, jobKeys.Count);
                var triggerKeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT"));

                Assert.AreEqual(2, triggerKeys.Count);
            }
            finally
            {
                if (scheduler != null)
                {
                    await scheduler.Shutdown();
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Creates a scheduler using the specified thread pool and job store and
        /// binds it for remote access.
        /// </summary>
        /// <param name="schedulerName">The name for the scheduler.</param>
        /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
        /// <param name="threadPool">The thread pool for executing jobs</param>
        /// <param name="threadExecutor">Thread executor.</param>
        /// <param name="jobStore">The type of job store</param>
        /// <param name="schedulerPluginMap"></param>
        /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for
        /// the default value, which is currently 30000 ms.</param>
        /// <param name="dbFailureRetryInterval">The db failure retry interval.</param>
        /// <param name="maxBatchSize">The maximum batch size of triggers, when acquiring them</param>
        /// <param name="batchTimeWindow">The time window for which it is allowed to "pre-acquire" triggers to fire</param>
        public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IThreadExecutor threadExecutor,
                                            IJobStore jobStore, IDictionary <string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime,
                                            TimeSpan dbFailureRetryInterval, int maxBatchSize, TimeSpan batchTimeWindow)
        {
            // Currently only one run-shell factory is available...
            IJobRunShellFactory jrsf = new StdJobRunShellFactory();

            // Fire everything u
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            threadPool.Initialize();

            QuartzSchedulerResources qrs = new QuartzSchedulerResources();

            qrs.Name       = schedulerName;
            qrs.InstanceId = schedulerInstanceId;

            SchedulerDetailsSetter.SetDetails(threadPool, schedulerName, schedulerInstanceId);

            qrs.JobRunShellFactory = jrsf;
            qrs.ThreadPool         = threadPool;
            qrs.ThreadExecutor     = threadExecutor;
            qrs.JobStore           = jobStore;
            qrs.MaxBatchSize       = maxBatchSize;
            qrs.BatchTimeWindow    = batchTimeWindow;

            // add plugins
            if (schedulerPluginMap != null)
            {
                foreach (ISchedulerPlugin plugin in schedulerPluginMap.Values)
                {
                    qrs.AddSchedulerPlugin(plugin);
                }
            }

            QuartzScheduler qs = new QuartzScheduler(qrs, idleWaitTime, dbFailureRetryInterval);

            ITypeLoadHelper cch = new SimpleTypeLoadHelper();

            cch.Initialize();

            SchedulerDetailsSetter.SetDetails(jobStore, schedulerName, schedulerInstanceId);
            jobStore.Initialize(cch, qs.SchedulerSignaler);

            IScheduler scheduler = new StdScheduler(qs);

            jrsf.Initialize(scheduler);

            qs.Initialize();

            // Initialize plugins now that we have a Scheduler instance.
            if (schedulerPluginMap != null)
            {
                foreach (var pluginEntry in schedulerPluginMap)
                {
                    pluginEntry.Value.Initialize(pluginEntry.Key, scheduler);
                }
            }

            SchedulerService schedRep = SchedulerService.Instance;

            qs.AddNoGCObject(schedRep); // prevents the service from being
            // garbage collected

            schedRep.Bind(scheduler);

            initialized = true;
        }
        /// <summary>
        /// Creates a scheduler using the specified thread pool and job store and
        /// binds it for remote access.
        /// </summary>
        /// <param name="schedulerName">The name for the scheduler.</param>
        /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param>
        /// <param name="threadPool">The thread pool for executing jobs</param>
        /// <param name="jobStore">The type of job store</param>
        /// <param name="schedulerPluginMap"></param>
        /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for
        ///     the default value, which is currently 30000 ms.</param>
        /// <param name="maxBatchSize">The maximum batch size of triggers, when acquiring them</param>
        /// <param name="batchTimeWindow">The time window for which it is allowed to "pre-acquire" triggers to fire</param>
        /// <param name="schedulerExporter">The scheduler exporter to use</param>
        public virtual void CreateScheduler(
            string schedulerName,
            string schedulerInstanceId,
            IThreadPool threadPool,
            IJobStore jobStore,
            IDictionary <string, ISchedulerPlugin> schedulerPluginMap,
            TimeSpan idleWaitTime,
            int maxBatchSize,
            TimeSpan batchTimeWindow,
            ISchedulerExporter schedulerExporter)
        {
            // Currently only one run-shell factory is available...
            IJobRunShellFactory jrsf = new StdJobRunShellFactory();

            // Fire everything up
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            SchedulerDetailsSetter.SetDetails(threadPool, schedulerName, schedulerInstanceId);

            threadPool.Initialize();

            QuartzSchedulerResources qrs = new QuartzSchedulerResources
            {
                Name       = schedulerName,
                InstanceId = schedulerInstanceId,

                JobRunShellFactory = jrsf,
                ThreadPool         = threadPool,
                JobStore           = jobStore,
                MaxBatchSize       = maxBatchSize,
                BatchTimeWindow    = batchTimeWindow,
                SchedulerExporter  = schedulerExporter
            };

            // add plugins
            if (schedulerPluginMap != null)
            {
                foreach (ISchedulerPlugin plugin in schedulerPluginMap.Values)
                {
                    qrs.AddSchedulerPlugin(plugin);
                }
            }

            QuartzScheduler qs = new QuartzScheduler(qrs, idleWaitTime);

            ITypeLoadHelper cch = new SimpleTypeLoadHelper();

            cch.Initialize();

            SchedulerDetailsSetter.SetDetails(jobStore, schedulerName, schedulerInstanceId);
            jobStore.Initialize(cch, qs.SchedulerSignaler);

            IScheduler scheduler = new StdScheduler(qs);

            jrsf.Initialize(scheduler);

            qs.Initialize();

            // Initialize plugins now that we have a Scheduler instance.
            if (schedulerPluginMap != null)
            {
                foreach (var pluginEntry in schedulerPluginMap)
                {
                    pluginEntry.Value.Initialize(pluginEntry.Key, scheduler);
                }
            }

            Log.Info($"Quartz scheduler '{scheduler.SchedulerName}");

            Log.Info($"Quartz scheduler version: {qs.Version}");

            SchedulerRepository schedRep = SchedulerRepository.Instance;

            qs.AddNoGCObject(schedRep); // prevents the repository from being
            // garbage collected

            schedRep.Bind(scheduler);

            initialized = true;
        }