Ejemplo n.º 1
0
        public async Task ScheduleJobAsync(InternalBuilder jobBuilder)
        {
            jobBuilder.Build();

            var jobKey     = new JobKey(jobBuilder.JobData.JobName, jobBuilder.JobData.JobGroup);
            var triggerKey = new TriggerKey(jobBuilder.JobData.TriggerName, jobBuilder.JobData.JobGroup);

            var data = new JobDataMap();

            data.Add("builder", jobBuilder);

            var job = JobBuilder.Create <GenericQuartzJob>()
                      .WithIdentity(jobKey)
                      .UsingJobData(data)
                      .Build();

            var triggerBuilder = TriggerBuilder.Create()
                                 .WithIdentity(triggerKey);

            if (jobBuilder.JobStartDate.HasValue)
            {
                triggerBuilder = triggerBuilder.StartAt((DateTimeOffset)jobBuilder.JobStartDate.Value);
            }
            else
            {
                triggerBuilder = triggerBuilder.StartNow();
            }

            ITrigger trigger;

            if (typeof(IDateJob).IsAssignableFrom(jobBuilder.JobType) && jobBuilder.JobStartDate.HasValue)
            {
                trigger = triggerBuilder
                          .Build();
            }
            else
            {
                trigger = triggerBuilder
                          .WithSimpleSchedule((schedule) =>
                {
                    if (jobBuilder.JobDelay.HasValue)
                    {
                        schedule.WithInterval(jobBuilder.JobDelay.Value);
                    }

                    if (jobBuilder.Infinite)
                    {
                        schedule.RepeatForever();
                    }
                })
                          .Build();
            }

            if (await Scheduler.CheckExists(jobKey))
            {
                await Scheduler.RescheduleJob(triggerKey, trigger);
            }
            else
            {
                await Scheduler.ScheduleJob(job, trigger);
            }
        }
        /// <summary>
        /// Start to schedule all Quartz.NET jobs.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseQuartzJobs(this IApplicationBuilder app)
        {
            IServiceProvider provider = app.ApplicationServices;

            // SetUp Logger
            ILoggerFactory loggerFactory = provider.GetService <ILoggerFactory>();
            ILogger        logger        = loggerFactory?.CreateLogger("Quartz.NET");

            LogProvider.IsDisabled = true;
            LogProvider.SetCurrentLogProvider(new QuartzLogProvider(loggerFactory));

            // SetUp Jobs & Triggers
            IList <QuartaJobMeta>  jobs             = new List <QuartaJobMeta>();
            ISchedulerFactory      schedulerFactory = provider.GetRequiredService <ISchedulerFactory>();
            IScheduler             scheduler        = schedulerFactory?.GetScheduler().ConfigureAwait(false).GetAwaiter().GetResult();
            QuartzJobTypeContainer container        = provider.GetService <QuartzJobTypeContainer>();

            if (container != null)
            {
                foreach (Type type in container)
                {
                    QuartzJobAttribute attribute = type.GetCustomAttributes(typeof(QuartzJobAttribute), true).FirstOrDefault() as QuartzJobAttribute;
                    if (attribute == null)
                    {
                        logger?.LogWarning("QuartzJobAttribute is not found in class \"{0}\".", type.FullName);
                        continue;
                    }

                    string     jobName   = string.IsNullOrEmpty(attribute.Name) ? type.Name : attribute.Name;
                    IJobDetail jobDetail = JobBuilder.Create()
                                           .OfType(type)
                                           .WithIdentity(jobName, attribute.Group)
                                           .RequestRecovery(attribute.RequestRecovery)
                                           .StoreDurably(attribute.StoreDurably)
                                           .Build();
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(jobName + "Trigger", attribute.Group)
                                       .WithPriority(attribute.Priority)
                                       .WithCronSchedule(attribute.CronExpression, builder => builder.InTimeZone(TimeZoneInfo.Local))
                                       .ForJob(jobDetail)
                                       .StartNow()
                                       .Build();

                    jobs.Add(new QuartaJobMeta(jobDetail, trigger));
                }
            }

#if NETCOREAPP2_X
            IApplicationLifetime lifetime = provider.GetService <IApplicationLifetime>();
#else
            Microsoft.Extensions.Hosting.IHostApplicationLifetime lifetime = provider.GetService <Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
#endif
            if (lifetime != null)
            {
                // Follow the LifeCycle of ASP.NET Core
                lifetime.ApplicationStarted.Register(async() =>
                {
                    await Task.WhenAll(jobs.Select(e =>
                    {
                        logger?.LogInformation("Ready to schedule job \"{0}\".", e.JobDetail.Key.Name);
                        return(scheduler.ScheduleJob(e.JobDetail, e.Trigger));
                    }));
                    await scheduler.Start();
                });
                lifetime.ApplicationStopping.Register(async() =>
                {
                    if (!scheduler.IsShutdown)
                    {
                        await scheduler.Shutdown(false);
                    }
                });
            }
            else
            {
                // Here we go!
                Task.WhenAll(jobs.Select(e =>
                {
                    logger?.LogInformation("Ready to schedule job \"{0}\".", e.JobDetail.Key.Name);
                    return(scheduler.ScheduleJob(e.JobDetail, e.Trigger));
                })).Wait();
                scheduler.Start().Wait();
            }

            return(app);
        }