Beispiel #1
0
        public static IServiceCollection RegisterJobSchedulerServices(this IServiceCollection services, IConfiguration configuration)
        {
            // TODO: impelement job scheduler persistence
            // var connectionString = configuration?.GetSection("ConnectionStrings")?["Quartz"];
            //
            // if (connectionString == null)
            //     throw new InvalidOperationException("Quartz connection string not setup.");

            services.AddSingleton <ISchedulerFactory>(provider =>
            {
                var quartzSchedulerBuilder = SchedulerBuilder.Create();
                // quartzSchedulerBuilder.UsePersistentStore(
                //     options =>
                //     {
                //         //options.UseProperties = true;
                //         options.UsePostgres(connectionString);
                //         options.UseJsonSerializer();
                //     }
                // );
                return(quartzSchedulerBuilder.Build());
            });
            services.AddSingleton <IScheduler, DependencyInjectionQuartzScheduler>();
            services.AddSingleton <IJobFactory, DependencyInjectionQuartzJobFactory>();

            return(services);
        }
Beispiel #2
0
        public void TestTimeZonePlugin()
        {
            var builder = SchedulerBuilder.Create()
                          .UseTimeZoneConverter();

            Assert.That(builder.Properties["quartz.plugin.timeZoneConverter.type"], Is.EqualTo(typeof(TimeZoneConverterPlugin).AssemblyQualifiedNameWithoutVersion()));
        }
Beispiel #3
0
        private async Task RunAdoJobStoreTest(
            string dbProvider,
            string connectionStringId,
            string serializerType,
            NameValueCollection extraProperties,
            bool clustered = true)
        {
            var config = SchedulerBuilder.Create("instance_one", "TestScheduler");

            config.UseDefaultThreadPool(x =>
            {
                x.MaxConcurrency = 10;
            });
            config.MisfireThreshold = TimeSpan.FromSeconds(60);

            config.UsePersistentStore(store =>
            {
                store.UseProperties = false;

                if (clustered)
                {
                    store.UseClustering(c =>
                    {
                        c.CheckinInterval = TimeSpan.FromMilliseconds(1000);
                    });
                }

                store.UseGenericDatabase(dbProvider, db =>
                                         db.ConnectionString = dbConnectionStrings[connectionStringId]
                                         );

                if (serializerType == "json")
                {
                    store.UseJsonSerializer();
                }
                else
                {
                    store.UseBinarySerializer();
                }
            });

            if (extraProperties != null)
            {
                foreach (string key in extraProperties.Keys)
                {
                    config.SetProperty(key, extraProperties[key]);
                }
            }

            // Clear any old errors from the log
            FailFastLoggerFactoryAdapter.Errors.Clear();

            // First we must get a reference to a scheduler
            IScheduler sched = await config.BuildScheduler();

            SmokeTestPerformer performer = new SmokeTestPerformer();
            await performer.Test(sched, clearJobs, scheduleJobs);

            Assert.IsEmpty(FailFastLoggerFactoryAdapter.Errors, "Found error from logging output");
        }
Beispiel #4
0
        public void TestSqlServerJobStore()
        {
            var config = SchedulerBuilder.Create();

            config.UsePersistentStore(js =>
            {
                js.UseJsonSerializer();
                js.RetryInterval = TimeSpan.FromSeconds(20);
                js.UseClustering(c =>
                {
                    c.CheckinInterval         = TimeSpan.FromSeconds(10);
                    c.CheckinMisfireThreshold = TimeSpan.FromSeconds(15);
                });

                js.UseSqlServer(db =>
                {
                    db.ConnectionString = "Server=localhost;Database=quartznet;";
                    db.TablePrefix      = "QRTZ2019_";
                });
            });
            Assert.That(config.Properties["quartz.dataSource.default.connectionString"], Is.EqualTo("Server=localhost;Database=quartznet;"));

            Assert.That(config.Properties["quartz.jobStore.type"], Is.EqualTo(typeof(JobStoreTX).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.jobStore.driverDelegateType"], Is.EqualTo(typeof(SqlServerDelegate).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.jobStore.dataSource"], Is.EqualTo("default"));
            Assert.That(config.Properties["quartz.jobStore.tablePrefix"], Is.EqualTo("QRTZ2019_"));
            Assert.That(config.Properties["quartz.jobStore.clusterCheckinInterval"], Is.EqualTo("10000"));
            Assert.That(config.Properties["quartz.jobStore.clusterCheckinMisfireThreshold"], Is.EqualTo("15000"));
            Assert.That(config.Properties["quartz.jobStore.dbRetryInterval"], Is.EqualTo("20000"));
        }
Beispiel #5
0
        public void TestSqlServerJobStore()
        {
            var builder = SchedulerBuilder.Create()
                          .UsePersistentStore(persistence =>
                                              persistence
                                              .WithJsonSerializer()
                                              .Clustered(cluster => cluster
                                                         .WithCheckinInterval(TimeSpan.FromSeconds(10))
                                                         .WithCheckinMisfireThreshold(TimeSpan.FromSeconds(15))
                                                         )
                                              .UseSqlServer(db =>
                                                            db.WithConnectionString("Server=localhost;Database=quartznet;")
                                                            )
                                              .WithTablePrefix("QRTZ2019_")
                                              );

            Assert.That(builder.Properties["quartz.dataSource.default.connectionString"], Is.EqualTo("Server=localhost;Database=quartznet;"));

            Assert.That(builder.Properties["quartz.jobStore.type"], Is.EqualTo(typeof(JobStoreTX).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(builder.Properties["quartz.jobStore.driverDelegateType"], Is.EqualTo(typeof(SqlServerDelegate).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(builder.Properties["quartz.jobStore.dataSource"], Is.EqualTo("default"));
            Assert.That(builder.Properties["quartz.jobStore.tablePrefix"], Is.EqualTo("QRTZ2019_"));
            Assert.That(builder.Properties["quartz.jobStore.clusterCheckinInterval"], Is.EqualTo("10000"));
            Assert.That(builder.Properties["quartz.jobStore.clusterCheckinMisfireThreshold"], Is.EqualTo("15000"));
        }
        protected override Task <IScheduler> CreateScheduler(string name, int threadPoolSize)
        {
            var builder = SchedulerBuilder.Create()
                          .WithName(name + "Scheduler")
                          .WithId("AUTO")
                          .WithDefaultThreadPool(x => x.WithThreadCount(threadPoolSize));

            return(builder.Build());
        }
Beispiel #7
0
        protected override Task<IScheduler> CreateScheduler(string name, int threadPoolSize)
        {
            var config = SchedulerBuilder.Create()
                .SetSchedulerName(name + "Scheduler")
                .SetSchedulerId("AUTO");
            
            config.UseDefaultThreadPool(x => x.SetThreadCount(threadPoolSize));

            return config.BuildScheduler();
        }
Beispiel #8
0
        public void TestRamJobStore()
        {
            var config = SchedulerBuilder.Create();

            config.UseInMemoryStore();
            config.UseDefaultThreadPool(x => x.ThreadCount = 100);

            Assert.That(config.Properties["quartz.jobStore.type"], Is.EqualTo(typeof(RAMJobStore).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.threadPool.threadCount"], Is.EqualTo("100"));
        }
        public async Task Should_Create_Activity()
        {
            // Arrange
            Barrier         barrier           = new Barrier(2);
            List <DateTime> jobExecTimestamps = new List <DateTime>();

            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using var tel = Sdk.CreateTracerProviderBuilder()
                            .SetSampler(new AlwaysOnSampler())
                            .AddQuartzInstrumentation()
                            .AddProcessor(activityProcessor.Object)
                            .Build();
            var schedulerConfig = SchedulerBuilder.Create("AUTO", "Scheduler");

            schedulerConfig.UseDefaultThreadPool(x => x.MaxConcurrency = 10);
            var scheduler = await schedulerConfig.BuildScheduler();

            scheduler.Context.Put("BARRIER", barrier);
            scheduler.Context.Put("DATESTAMPS", jobExecTimestamps);
            await scheduler.Start();

            JobDataMap jobDataMap = new JobDataMap {
                { "A", "B" }
            };

            var name = Guid.NewGuid().ToString();
            var job  = JobBuilder.Create <TestJob>()
                       .WithIdentity(name, SchedulerConstants.DefaultGroup)
                       .UsingJobData(jobDataMap)
                       .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(name, SchedulerConstants.DefaultGroup)
                          .StartNow()
                          .Build();

            // Act
            await scheduler.ScheduleJob(job, trigger);

            barrier.SignalAndWait(TestTimeout);

            await scheduler.Shutdown(true);

            // Assert
            Assert.Equal(3, activityProcessor.Invocations.Count);
            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Contains("execute ", activity.DisplayName);
            Assert.Equal("Quartz.Job.Execute", activity.OperationName);
            Assert.Equal(ActivityKind.Internal, activity.Kind);
            Assert.Equal("Scheduler", activity.Tags.SingleOrDefault(t => t.Key.Equals("scheduler.name")).Value);
            Assert.Equal(SchedulerConstants.DefaultGroup, activity.Tags.SingleOrDefault(t => t.Key.Equals("job.group")).Value);
            Assert.Equal(SchedulerConstants.DefaultGroup, activity.Tags.SingleOrDefault(t => t.Key.Equals("trigger.group")).Value);
        }
        public async Task Should_Record_Exception_When_Record_Exception_Enabled()
        {
            // Arrange
            Barrier         barrier           = new Barrier(2);
            List <DateTime> jobExecTimestamps = new List <DateTime>();

            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using var tel = Sdk.CreateTracerProviderBuilder()
                            .SetSampler(new AlwaysOnSampler())
                            .AddQuartzInstrumentation(q =>
                                                      q.RecordException = true)
                            .AddProcessor(activityProcessor.Object)
                            .Build();

            var schedulerConfig = SchedulerBuilder.Create("AUTO", "Scheduler");

            schedulerConfig.UseDefaultThreadPool(x => x.MaxConcurrency = 10);
            var scheduler = await schedulerConfig.BuildScheduler();

            scheduler.Context.Put("BARRIER", barrier);
            scheduler.Context.Put("DATESTAMPS", jobExecTimestamps);
            await scheduler.Start();

            var        testId     = Guid.NewGuid().ToString();
            JobDataMap jobDataMap = new JobDataMap {
                { "TestId", testId }
            };

            var name = Guid.NewGuid().ToString();
            var job  = JobBuilder.Create <TestJobExecutionExceptionJob>()
                       .WithIdentity(name, SchedulerConstants.DefaultGroup)
                       .UsingJobData(jobDataMap)
                       .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(name, SchedulerConstants.DefaultGroup)
                          .StartNow()
                          .Build();

            // Act
            await scheduler.ScheduleJob(job, trigger);

            barrier.SignalAndWait(TimeSpan.FromSeconds(1));

            await scheduler.Shutdown(true);

            // Assert
            Assert.Equal(3, activityProcessor.Invocations.Count);
            var activity = (Activity)activityProcessor.Invocations[1].Arguments[0];

            Assert.Equal("exception", activity.Events.First().Name);
            Assert.Equal("ERROR", activity.Tags.SingleOrDefault(t => t.Key.Equals(SpanAttributeConstants.StatusCodeKey)).Value);
            Assert.Equal("Catch me if you can!", activity.Tags.SingleOrDefault(t => t.Key.Equals(SpanAttributeConstants.StatusDescriptionKey)).Value);
        }
        public async Task Should_Not_Record_Activity_When_Trace_Operation_Is_Not_Present()
        {
            // Arrange
            Barrier         barrier           = new Barrier(2);
            List <DateTime> jobExecTimestamps = new List <DateTime>();

            var activityProcessor = new Mock <BaseProcessor <Activity> >();

            using var tel = Sdk.CreateTracerProviderBuilder()
                            .SetSampler(new AlwaysOnSampler())
                            .AddQuartzInstrumentation(q =>
            {
                q.TracedOperations = new HashSet <string>();
            })
                            .AddProcessor(activityProcessor.Object)
                            .Build();

            var schedulerConfig = SchedulerBuilder.Create("AUTO", "Scheduler");

            schedulerConfig.UseDefaultThreadPool(x => x.MaxConcurrency = 10);
            var scheduler = await schedulerConfig.BuildScheduler();

            scheduler.Context.Put("BARRIER", barrier);
            scheduler.Context.Put("DATESTAMPS", jobExecTimestamps);
            await scheduler.Start();

            var        testId     = Guid.NewGuid().ToString();
            JobDataMap jobDataMap = new JobDataMap {
                { "TestId", testId }
            };

            var name = Guid.NewGuid().ToString();
            var job  = JobBuilder.Create <TestJob>()
                       .WithIdentity(name, SchedulerConstants.DefaultGroup)
                       .UsingJobData(jobDataMap)
                       .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(name, SchedulerConstants.DefaultGroup)
                          .StartNow()
                          .Build();

            // Act
            await scheduler.ScheduleJob(job, trigger);

            barrier.SignalAndWait(TestTimeout);

            await scheduler.Shutdown(true);

            // Assert
            var activities = activityProcessor.Invocations.SelectMany(i => i.Arguments.OfType <Activity>())
                             .Where(a => a.IsAllDataRequested);

            Assert.Empty(activities);
        }
        private static void _registerJobs(SchedulerBuilder builder, Type[] jobs)
        {
            Type[]     types  = new Type[] { };
            MethodInfo method = typeof(SchedulerBuilder).GetMethod(nameof(SchedulerBuilder.AddJob), types);

            foreach (Type job in jobs)
            {
                MethodInfo generic = method.MakeGenericMethod(job);
                generic.Invoke(builder, null);
            }
        }
        public static Task <IScheduler> CreateAndConfigureSchedulerAsync()
        {
            var runEvery = ConfigurationManager.AppSettings["runEvery"];
            var jobData  = new JobDataMap();

            jobData.SetExecutionData();
            return(SchedulerBuilder.Create()
                   .WithJobFactory(CreateJobFactory())
                   .ScheduleJob <MessageUpdater>(runEvery, jobData)
                   .BuildAsync());
        }
        protected override Task <IScheduler> CreateScheduler(string name, int threadPoolSize)
        {
            var config = SchedulerBuilder.Create("AUTO", name + "Scheduler");

            config.UseDefaultThreadPool(x =>
            {
                x.MaxConcurrency = threadPoolSize;
            });

            return(config.BuildScheduler());
        }
Beispiel #15
0
        public void TestSQLiteJsobStore()
        {
            var config = SchedulerBuilder.Create();

            config.UsePersistentStore(options =>
                                      options.UseSQLite("Server=localhost;Database=quartznet;")
                                      );
            Assert.That(config.Properties["quartz.dataSource.default.connectionString"], Is.EqualTo("Server=localhost;Database=quartznet;"));

            Assert.That(config.Properties["quartz.jobStore.type"], Is.EqualTo(typeof(JobStoreTX).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.jobStore.driverDelegateType"], Is.EqualTo(typeof(SQLiteDelegate).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.jobStore.dataSource"], Is.EqualTo("default"));
        }
Beispiel #16
0
        public void TestFirebirdJobStore()
        {
            var config = SchedulerBuilder.Create();

            config
            .UsePersistentStore(persistence =>
                                persistence.UseFirebird(db => db
                                                        .SetConnectionString("Server=localhost;Database=quartznet;"))
                                );
            Assert.That(config.Properties["quartz.dataSource.default.connectionString"], Is.EqualTo("Server=localhost;Database=quartznet;"));

            Assert.That(config.Properties["quartz.jobStore.type"], Is.EqualTo(typeof(JobStoreTX).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.jobStore.driverDelegateType"], Is.EqualTo(typeof(FirebirdDelegate).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(config.Properties["quartz.jobStore.dataSource"], Is.EqualTo("default"));
        }
Beispiel #17
0
        public void TestXmlSchedulingPlugin()
        {
            var builder = SchedulerBuilder.Create()
                          .UseXmlSchedulingConfiguration(x => x
                                                         .SetFiles("jobs.xml", "jobs2.xml")
                                                         .SetScanInterval(TimeSpan.FromSeconds(2))
                                                         .SetFailOnFileNotFound()
                                                         .SetFailOnSchedulingError()
                                                         );

            Assert.That(builder.Properties["quartz.plugin.xml.type"], Is.EqualTo(typeof(XMLSchedulingDataProcessorPlugin).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(builder.Properties["quartz.plugin.xml.fileNames"], Is.EqualTo("jobs.xml,jobs2.xml"));
            Assert.That(builder.Properties["quartz.plugin.xml.failOnFileNotFound"], Is.EqualTo("true"));
            Assert.That(builder.Properties["quartz.plugin.xml.failOnSchedulingError"], Is.EqualTo("true"));
            Assert.That(builder.Properties["quartz.plugin.xml.scanInterval"], Is.EqualTo("2"));
        }
Beispiel #18
0
        public void TestMySqlJobStore()
        {
            var builder = SchedulerBuilder.Create()
                          .UsePersistentStore(persistence =>
                                              persistence
                                              .UseMySql(db =>
                                                        db.WithConnectionString("Server=localhost;Database=quartznet;")
                                                        )
                                              );

            Assert.That(builder.Properties["quartz.dataSource.default.connectionString"], Is.EqualTo("Server=localhost;Database=quartznet;"));

            Assert.That(builder.Properties["quartz.jobStore.type"], Is.EqualTo(typeof(JobStoreTX).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(builder.Properties["quartz.jobStore.driverDelegateType"], Is.EqualTo(typeof(MySQLDelegate).AssemblyQualifiedNameWithoutVersion()));
            Assert.That(builder.Properties["quartz.jobStore.dataSource"], Is.EqualTo("default"));
        }
Beispiel #19
0
        public async Task Run()
        {
            Console.WriteLine("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            var sched = await SchedulerBuilder.Create()
                        .WithName("XmlConfiguredInstance")
                        .UseDefaultThreadPool(maxConcurrency: 5)
                        // job initialization plugin handles our xml reading, without it defaults are used
                        .UseXmlSchedulingConfiguration(x =>
            {
                x.Files = new[] { "~/quartz_jobs.xml" };
                // this is the default
                x.FailOnFileNotFound = true;
                // this is not the default
                x.FailOnSchedulingError = true;
            })
                        .BuildScheduler();

            // we need to add calendars manually, lets create a silly sample calendar
            var dailyCalendar = new DailyCalendar("00:01", "23:59");

            dailyCalendar.InvertTimeRange = true;
            await sched.AddCalendar("cal1", dailyCalendar, false, false);

            Console.WriteLine("------- Initialization Complete -----------");

            // all jobs and triggers are now in scheduler

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();

            Console.WriteLine("------- Started Scheduler -----------------");

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

            await Task.Delay(30 *1000);

            // shut down the scheduler
            Console.WriteLine("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            Console.WriteLine("------- Shutdown Complete -----------------");
        }
Beispiel #20
0
 public static SchedulerBuilder <T> Month <T>(this SchedulerBuilder <T> builder, string name)
     where T : class, ISchedulerEvent
 {
     return(builder
            .Name(name)
            .Views(views =>
     {
         views.MonthView(m => m.Title("Месяц")
                         .DayTemplate("<span>#=kendo.toString(date, \"dd\")#</span>"));
     })
            .Messages(messages =>
     {
         messages.Today("Сегодня");
     })
            .Editable(false)
            .Selectable(false));
 }
        public static void AddJobs(this SchedulerBuilder builder, params Assembly[] assembliesToScan)
        {
            foreach (var assembly in assembliesToScan)
            {
                var jobs = assembly
                           .GetTypes()
                           .Where(x =>
                                  x.GetInterfaces().Contains(typeof(IScheduledJob)) &&
                                  !x.IsAbstract &&
                                  !x.IsInterface &&
                                  x.IsClass
                                  )
                           .ToArray();

                _registerJobs(builder, jobs);
            }
        }
        private async Task RunAdoJobStoreTest(
            string dbProvider,
            string connectionStringId,
            string serializerType,
            NameValueCollection extraProperties,
            bool clustered = true)
        {
            var builder = SchedulerBuilder.Create("instance_one", "TestScheduler")
                          .WithDefaultThreadPool(x => x.WithThreadCount(10))
                          .WithMisfireThreshold(TimeSpan.FromSeconds(60))
                          .UsePersistentStore(store =>
            {
                var x = store
                        .UseProperties(false)
                        .Clustered(clustered, options => options.WithCheckinInterval(TimeSpan.FromMilliseconds(1000)))
                        .UseGenericDatabase(dbProvider, db => db.WithConnectionString(dbConnectionStrings[connectionStringId]));

                x = serializerType == "json"
                        ? x.WithJsonSerializer()
                        : x.WithBinarySerializer();
            });

            if (extraProperties != null)
            {
                foreach (string key in extraProperties.Keys)
                {
                    builder.SetProperty(key, extraProperties[key]);
                }
            }

            // Clear any old errors from the log
            FailFastLoggerFactoryAdapter.Errors.Clear();

            // First we must get a reference to a scheduler
            IScheduler sched = await builder.Build();

            SmokeTestPerformer performer = new SmokeTestPerformer();
            await performer.Test(sched, clearJobs, scheduleJobs);

            Assert.IsEmpty(FailFastLoggerFactoryAdapter.Errors, "Found error from logging output");
        }
        public virtual async Task Run()
        {
            // First we must get a reference to a scheduler
            IScheduler sched = await SchedulerBuilder.Create()
                               .WithName("RemoteClient")
                               .UseDefaultThreadPool(x => x.MaxConcurrency = 5)
                               .ProxyToRemoteScheduler("tcp://127.0.0.1:555/QuartzScheduler")
                               .BuildScheduler();

            // define the job and ask it to run

            IJobDetail job = JobBuilder.Create <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)
                               .WithCronSchedule("/5 * * ? * *")
                               .Build();

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

            Console.WriteLine("Remote job scheduled, scheduler now has following jobs:");

            var keys = await sched.GetJobKeys(GroupMatcher <JobKey> .AnyGroup());

            foreach (var key in keys)
            {
                Console.WriteLine("\t " + key);
            }
        }
        public async Task Run()
        {
            Console.WriteLine("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            var sched = await SchedulerBuilder.Create()
                        .WithName("PriorityExampleScheduler")
                        // Set thread count to 1 to force Triggers scheduled for the same time to
                        // to be ordered by priority.
                        .UseDefaultThreadPool(1)
                        .BuildScheduler();

            Console.WriteLine("------- Initialization Complete -----------");

            Console.WriteLine("------- Scheduling Jobs -------------------");

            IJobDetail job = JobBuilder.Create <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. Priority1Trigger5SecondRepeat
            // 4. Priority1Trigger5SecondRepeat
            // 5. Priority5Trigger10SecondRepeat
            // 6. Priority10Trigger15SecondRepeat

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

            // First trigger has priority of 1, and will repeat after 5 seconds
            ITrigger trigger1 = TriggerBuilder.Create()
                                .WithIdentity("Priority1Trigger5SecondRepeat")
                                .StartAt(startTime)
                                .WithSimpleSchedule(x => x.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)
                                .WithSimpleSchedule(x => x.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)
                                .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(15))
                                .WithPriority(10)
                                .ForJob(job)
                                .Build();

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

            await sched.ScheduleJob(trigger2);

            await sched.ScheduleJob(trigger3);

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();

            Console.WriteLine("------- Started Scheduler -----------------");

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

            await Task.Delay(TimeSpan.FromSeconds(30));

            // shut down the scheduler
            Console.WriteLine("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            Console.WriteLine("------- Shutdown Complete -----------------");
        }
Beispiel #25
0
        public virtual async Task Run(bool inClearJobs, bool inScheduleJobs)
        {
            // First we must get a reference to a scheduler
            IScheduler sched = await SchedulerBuilder.Create()
                               .WithId("instance_one")
                               .WithName("TestScheduler")
                               .UseDefaultThreadPool(x => x.MaxConcurrency = 5)
                               .WithMisfireThreshold(TimeSpan.FromSeconds(60))
                               .UsePersistentStore(x =>
            {
                x.UseProperties = true;
                x.UseClustering();
                x.UseSqlServer(TestConstants.SqlServerConnectionString);
                x.UseJsonSerializer();
            })
                               .BuildScheduler();

            // if running SQLite we need this
            // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";

            if (inClearJobs)
            {
                Console.WriteLine("***** Deleting existing jobs/triggers *****");
                await sched.Clear();
            }

            Console.WriteLine("------- Initialization Complete -----------");

            if (inScheduleJobs)
            {
                Console.WriteLine("------- Scheduling Jobs ------------------");

                string schedId = sched.SchedulerInstanceId;

                int count = 1;

                IJobDetail job = JobBuilder.Create <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, IntervalUnit.Second))
                                         .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5)))
                                         .Build();

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

                count++;

                job = JobBuilder.Create <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, IntervalUnit.Second))
                          .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5)))
                          .Build();

                Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds");
                await sched.ScheduleJob(job, trigger);

                count++;

                job = JobBuilder.Create <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, IntervalUnit.Second))
                          .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(3)))
                          .Build();

                Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds");
                await sched.ScheduleJob(job, trigger);

                count++;

                job = JobBuilder.Create <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, IntervalUnit.Second))
                          .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(4)))
                          .Build();

                Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}");
                await sched.ScheduleJob(job, trigger);

                count++;

                job = JobBuilder.Create <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, IntervalUnit.Second))
                          .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromMilliseconds(4500)))
                          .Build();

                Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}");
                await sched.ScheduleJob(job, trigger);
            }

            // jobs don't start firing until start() has been called...
            Console.WriteLine("------- Starting Scheduler ---------------");
            await sched.Start();

            Console.WriteLine("------- Started Scheduler ----------------");

            Console.WriteLine("------- Waiting for one hour... ----------");

            await Task.Delay(TimeSpan.FromHours(1));

            Console.WriteLine("------- Shutting Down --------------------");
            await sched.Shutdown();

            Console.WriteLine("------- Shutdown Complete ----------------");
        }