Пример #1
0
        private static void ConfigureJob(ServiceConfigurator configurator, Action <QuartzConfigurator> jobConfigurator)
        {
            var jobConfig = new QuartzConfigurator();

            jobConfigurator(jobConfig);

            if (jobConfig.JobEnabled == null || jobConfig.JobEnabled() || (jobConfig.Job == null || jobConfig.Triggers == null))
            {
                var jobDetail = jobConfig.Job != null?jobConfig.Job() : null;

                var jobTriggers = (jobConfig.Triggers ?? Enumerable.Empty <Func <ITrigger> >())
                                  .Select(triggerFactory => triggerFactory()).Where(trigger => trigger != null).ToArray();

                configurator.BeforeStartingService(() => {
                    _scheduler = _scheduler ?? GetScheduler();
                    if (_scheduler == null || jobDetail == null || !jobTriggers.Any())
                    {
                        return;
                    }

                    var triggersForJob = new global::Quartz.Collection.HashSet <ITrigger>(jobTriggers);
                    _scheduler.ScheduleJob(jobDetail, triggersForJob, false);
                    _scheduler.Start();
                });
                configurator.BeforeStoppingService(() => _scheduler.Shutdown(true));
            }
        }
Пример #2
0
        /// <summary>
        ///     Registers a Rebus bus which will be automatically started along with the Topshelf service
        /// </summary>
        /// <remarks>
        ///     The current bus instance can be accessed on <see cref="RebusService.Bus"/>
        /// </remarks>
        public static ServiceConfigurator <T> Rebus <T>(this ServiceConfigurator <T> configurator,
                                                        IHandlerActivator handlerActivator, Action <RebusConfigurer> rebusConfigurer)
            where T : class
        {
            if (configurator == null)
            {
                throw new ArgumentNullException(nameof(configurator));
            }
            if (rebusConfigurer == null)
            {
                throw new ArgumentNullException(nameof(rebusConfigurer));
            }
            if (handlerActivator == null)
            {
                throw new ArgumentNullException(nameof(handlerActivator));
            }

            var configurer = Configure.With(handlerActivator);

            rebusConfigurer.Invoke(configurer);

            configurator.BeforeStartingService(host => Bus = configurer.Start());
            configurator.BeforeStoppingService(host => Bus?.Dispose());

            return(configurator);
        }
Пример #3
0
        private static void ConfigureJob <T>(ServiceConfigurator <T> configurator, Action <JobConfigurator> jobConfigurator, bool replaceJob = false) where T : class
        {
            var log = HostLogger.Get(typeof(ScheduleJobServiceConfiguratorExtensions));

            var jobConfig = new JobConfigurator();

            jobConfigurator(jobConfig);

            if ((jobConfig.JobEnabled == null || jobConfig.JobEnabled()) && jobConfig.Job != null && jobConfig.Triggers != null)
            {
                var jobDetail   = jobConfig.Job();
                var jobTriggers = jobConfig.Triggers.Select(triggerFactory => triggerFactory()).Where(trigger => trigger != null).ToHashSet()
#if NET452
                                  .ToArray()
#endif
                ;

                async Task BeforeStartingServiceFunc()
                {
                    log.Debug("[Topshelf.Quartz] Scheduler starting up...");

                    var scheduler = await GetScheduler();

                    if (scheduler != null && jobDetail != null && jobTriggers.Any())
                    {
                        await scheduler.ScheduleJob(jobDetail, jobTriggers, replaceJob);

                        log.Info($"[Topshelf.Quartz] Scheduled Job: {jobDetail.Key} of Type: {jobDetail.JobType.Name}");

                        foreach (var trigger in jobTriggers)
                        {
                            log.Info($"[Topshelf.Quartz] Job Schedule: {trigger} - Next Fire Time (local): {trigger.GetNextFireTimeUtc()?.ToLocalTime().ToString() ?? "none"}");
                        }

                        await scheduler.Start();

                        log.Info("[Topshelf.Quartz] Scheduler started...");
                    }
                }

                async Task BeforeStoppingServiceFunc()
                {
                    log.Debug("[Topshelf.Quartz] Scheduler shutting down...");
                    var scheduler = await GetScheduler();

                    if (scheduler != null)
                    {
                        if (!scheduler.IsShutdown)
                        {
                            await scheduler.Shutdown();
                        }
                    }
                    log.Info("[Topshelf.Quartz] Scheduler shut down...");
                }

                configurator.BeforeStartingService(async() => await BeforeStartingServiceFunc());
                configurator.BeforeStoppingService(async() => await BeforeStoppingServiceFunc());
            }
        }
        private static void ConfigureJob <T>(ServiceConfigurator <T> configurator, Action <QuartzConfigurator> jobConfigurator) where T : class
        {
            var log = HostLogger.Get(typeof(ScheduleJobServiceConfiguratorExtensions));

            var jobConfig = new QuartzConfigurator();

            jobConfigurator(jobConfig);

            if (jobConfig.JobEnabled == null || jobConfig.JobEnabled() || (jobConfig.Job == null || jobConfig.Triggers == null))
            {
                var jobDetail   = jobConfig.Job();
                var jobTriggers = jobConfig.Triggers.Select(triggerFactory => triggerFactory()).Where(trigger => trigger != null);

                configurator.BeforeStartingService(() =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler starting up...");
                    if (Scheduler == null)
                    {
                        Scheduler = GetScheduler();
                    }


                    if (Scheduler != null && jobDetail != null && jobTriggers.Any())
                    {
                        var triggersForJob = new HashSet <ITrigger>(jobTriggers);
                        Scheduler.ScheduleJob(jobDetail, triggersForJob, false);
                        log.Info(string.Format("[Topshelf.Quartz] Scheduled Job: {0}", jobDetail.Key));

                        foreach (var trigger in triggersForJob)
                        {
                            log.Info(string.Format("[Topshelf.Quartz] Job Schedule: {0} - Next Fire Time (local): {1}", trigger, trigger.GetNextFireTimeUtc().HasValue ? trigger.GetNextFireTimeUtc().Value.ToLocalTime().ToString() : "none"));
                        }

                        Scheduler.Start();
                        log.Info("[Topshelf.Quartz] Scheduler started...");
                    }
                });

                configurator.BeforeStoppingService(() =>
                {
                    log.Info("[Topshelf.Quartz] Scheduler shutting down...");

                    var executingJobs = Scheduler.GetCurrentlyExecutingJobs();
                    foreach (var job in executingJobs)
                    {
                        log.InfoFormat("[Topshelf.Quartz] Attempt to interrupt currently executing job: {0}", job.JobDetail.JobType);
                        if (job.JobInstance.GetType().GetInterfaces().Contains(typeof(IInterruptableJob)))
                        {
                            ((IInterruptableJob)job.JobInstance).Interrupt();
                        }
                    }
                    Scheduler.Shutdown(true);
                    log.Info("[Topshelf.Quartz] Scheduler shut down...");
                });
            }
        }
Пример #5
0
        public static ServiceConfigurator <T> WebApiEndpoint <T>(this ServiceConfigurator <T> configurator, Action <WebApiConfigurator> webConfigurator) where T : class
        {
            WebApiConfigurator config = new WebApiConfigurator();

            webConfigurator(config);
            config.Build();
            configurator.BeforeStartingService(t => config.Server.OpenAsync().Wait());
            configurator.BeforeStoppingService(t => config.Server.CloseAsync().Wait());
            return(configurator);
        }
        public static ServiceConfigurator <T> OwinEndpoint <T>(this ServiceConfigurator <T> configurator, Action <WebAppConfigurator> appConfigurator = null) where T : class
        {
            var config = new WebAppConfigurator();

            appConfigurator?.Invoke(config);

            configurator.BeforeStartingService(t => config.Start());
            configurator.AfterStoppingService(t => config.Stop());

            return(configurator);
        }
Пример #7
0
        public static ServiceConfigurator <T> WebApiEndpoint <T>(this ServiceConfigurator <T> configurator, Action <WebApiConfigurator> webConfigurator) where T : class
        {
            var config = new WebApiConfigurator();

            webConfigurator(config);

            configurator.BeforeStartingService(t => config.Initialize());
            configurator.BeforeStoppingService(t => config.Shutdown());

            return(configurator);
        }
        private static void BeforeStartingService <T>(ServiceConfigurator <T> configurator,
                                                      IEnumerable <FileSystemWatcherConfigurator.DirectoryConfiguration> configs, LogWriter log,
                                                      FileSystemEventHandler watcherOnChanged,
                                                      FileSystemEventHandler watcherOnCreated,
                                                      FileSystemEventHandler watcherOnDeleted) where T : class
        {
            configurator.BeforeStartingService(() =>
            {
                foreach (FileSystemWatcherConfigurator.DirectoryConfiguration config in configs)
                {
                    if (!Directory.Exists(config.Path))
                    {
                        if (config.CreateDir)
                        {
                            log.Debug($"[Topshelf.FileSystemWatcher] Path ({config.Path}) does not exist. Creating...");
                            Directory.CreateDirectory(config.Path);
                        }
                        else
                        {
                            throw new DirectoryNotFoundException($"{config.Path} does not exist. Please call CreateDir in the FileSystemWatcherConfigurator, or make sure the dirs exist in the FileSystem");
                        }
                    }

                    var fileSystemWatcher = CreateFileSystemWatcher(config.Path, config.NotifyFilters, config.FileFilter, config.IncludeSubDirectories, config.InternalBufferSize);

                    if (watcherOnChanged != null)
                    {
                        fileSystemWatcher.Changed += watcherOnChanged;
                    }
                    if (watcherOnCreated != null)
                    {
                        fileSystemWatcher.Created += watcherOnCreated;
                    }
                    if (watcherOnDeleted != null)
                    {
                        fileSystemWatcher.Deleted += watcherOnDeleted;
                    }

                    _watchers.Add(fileSystemWatcher);

                    log.Info($"[Topshelf.FileSystemWatcher] configured to listen for events in {config.Path}");

                    foreach (System.IO.FileSystemWatcher watcher in _watchers)
                    {
                        watcher.EnableRaisingEvents = true;
                    }

                    log.Info("[Topshelf.FileSystemWatcher] listening for events");
                }
            });
        }
Пример #9
0
        private static void ConfigureJob <T>(ServiceConfigurator <T> configurator, Action <QuartzConfigurator> jobConfigurator) where T : class
        {
            var log = HostLogger.Get(typeof(ScheduleJobServiceConfiguratorExtensions));

            var jobConfig = new QuartzConfigurator();

            jobConfigurator(jobConfig);

            if (jobConfig.JobEnabled == null || jobConfig.JobEnabled() || jobConfig.Job == null || jobConfig.Triggers == null)
            {
                var jobDetail   = jobConfig.Job();
                var jobTriggers = jobConfig.Triggers.Select(triggerFactory => triggerFactory()).Where(trigger => trigger != null);

                configurator.BeforeStartingService(() =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler starting up...");
                    if (Scheduler == null)
                    {
                        Scheduler = GetScheduler();
                    }

                    if (Scheduler != null)
                    {
                        if (jobDetail != null && jobTriggers.Any())
                        {
                            var triggersForJob = new HashSet <ITrigger>(jobTriggers);
                            Scheduler.ScheduleJob(jobDetail, triggersForJob, false);
                            log.Info($"[Topshelf.Quartz] Scheduled Job: {jobDetail.Key}");

                            foreach (var trigger in triggersForJob)
                            {
                                log.Info($"[Topshelf.Quartz] Job Schedule: {trigger} - Next Fire Time (local): {(trigger.GetNextFireTimeUtc().HasValue ? trigger.GetNextFireTimeUtc().Value.ToLocalTime().ToString() : "none")}");
                            }

                            if (!Scheduler.IsStarted)
                            {
                                Scheduler.Start();
                                log.Info("[Topshelf.Quartz] Scheduler started...");
                            }
                        }

                        foreach (Tuple <Func <IJobListener>, IMatcher <JobKey>[]> jobListenerTuple in jobConfig.JobListeners)
                        {
                            IJobListener jobListener      = jobListenerTuple.Item1();
                            IMatcher <JobKey>[] keyEquals = jobListenerTuple.Item2;

                            if (jobListener != null)
                            {
                                Scheduler.ListenerManager.AddJobListener(jobListener, keyEquals);
                            }
                        }
                    }
                });

                configurator.BeforeStoppingService(() =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler shutting down...");
                    Scheduler.Shutdown(true);
                    log.Info("[Topshelf.Quartz] Scheduler shut down...");
                });
            }
        }
        private static void ConfigureJob <T>(ServiceConfigurator <T> configurator, Action <QuartzConfigurator> jobConfigurator, bool replaceJob = false) where T : class
        {
            var log = HostLogger.Get(typeof(ScheduleJobServiceConfiguratorExtensions));

            var jobConfig = new QuartzConfigurator();

            jobConfigurator(jobConfig);

            if (jobConfig.JobEnabled == null || jobConfig.JobEnabled() || (jobConfig.Job == null || jobConfig.Triggers == null))
            {
                var jobDetail         = jobConfig.Job();
                var jobTriggers       = jobConfig.Triggers.Select(triggerFactory => triggerFactory()).Where(trigger => trigger != null);
                var jobListeners      = jobConfig.JobListeners;
                var triggerListeners  = jobConfig.TriggerListeners;
                var scheduleListeners = jobConfig.ScheduleListeners;
                configurator.BeforeStartingService(() =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler starting up...");
                    if (Scheduler == null)
                    {
                        Scheduler = GetScheduler();
                    }


                    if (Scheduler != null && jobDetail != null && jobTriggers.Any())
                    {
                        var triggersForJob = new HashSet <ITrigger>(jobTriggers);
                        Scheduler.ScheduleJob(jobDetail, triggersForJob, replaceJob);
                        log.Info(string.Format("[Topshelf.Quartz] Scheduled Job: {0}", jobDetail.Key));

                        foreach (var trigger in triggersForJob)
                        {
                            log.Info(string.Format("[Topshelf.Quartz] Job Schedule: {0} - Next Fire Time (local): {1}", trigger, trigger.GetNextFireTimeUtc().HasValue ? trigger.GetNextFireTimeUtc().Value.ToLocalTime().ToString() : "none"));
                        }

                        if (jobListeners.Any())
                        {
                            foreach (var listener in jobListeners)
                            {
                                var config = listener();
                                Scheduler.ListenerManager.AddJobListener(
                                    config.Listener, config.Matchers);
                                log.Info(
                                    string.Format(
                                        "[Topshelf.Quartz] Added Job Listener: {0}",
                                        config.Listener.Name));
                            }
                        }

                        if (triggerListeners.Any())
                        {
                            foreach (var listener in triggerListeners)
                            {
                                var config = listener();
                                Scheduler.ListenerManager.AddTriggerListener(config.Listener, config.Matchers);
                                log.Info(
                                    string.Format(
                                        "[Topshelf.Quartz] Added Trigger Listener: {0}",
                                        config.Listener.Name));
                            }
                        }
                        if (scheduleListeners.Any())
                        {
                            foreach (var listener in scheduleListeners)
                            {
                                var schedListener = listener();
                                Scheduler.ListenerManager.AddSchedulerListener(schedListener);
                                string.Format(
                                    "[Topshelf.Quartz] Added Schedule Listener: {0}",
                                    schedListener.GetType());
                            }
                        }

                        Scheduler.Start();
                        log.Info("[Topshelf.Quartz] Scheduler started...");
                    }
                });

                configurator.BeforeStoppingService(() =>
                {
                    log.Debug("[Topshelf.Quartz] Scheduler shutting down...");
                    if (Scheduler != null)
                    {
                        if (!Scheduler.IsShutdown)
                        {
                            Scheduler.Shutdown();
                        }
                    }
                    log.Info("[Topshelf.Quartz] Scheduler shut down...");
                });
            }
        }
Пример #11
0
        private static void BeforeStartingService <T>(ServiceConfigurator <T> configurator,
                                                      IEnumerable <FileSystemWatcherConfigurator.DirectoryConfiguration> configs, LogWriter log,
                                                      FileSystemEventHandler watcherOnChanged,
                                                      FileSystemEventHandler watcherOnCreated,
                                                      RenamedEventHandler watcherOnRenamed,
                                                      FileSystemEventHandler watcherOnDeleted) where T : class
        {
            configurator.BeforeStartingService(() =>
            {
                foreach (FileSystemWatcherConfigurator.DirectoryConfiguration config in configs)
                {
                    if (!Directory.Exists(config.Path))
                    {
                        if (config.CreateDir)
                        {
                            log.Debug($"[Topshelf.FileSystemWatcher] Path ({config.Path}) does not exist. Creating...");
                            Directory.CreateDirectory(config.Path);
                        }
                        else
                        {
                            throw new DirectoryNotFoundException($"{config.Path} does not exist. Please call CreateDir in the FileSystemWatcherConfigurator, or make sure the dirs exist in the FileSystem");
                        }
                    }

                    var fileSystemWatcher = CreateFileSystemWatcher(config.Path, config.NotifyFilters, config.FileFilter, config.IncludeSubDirectories, config.InternalBufferSize);

                    if (config.ExcludeDuplicateEvents)
                    {
                        if (watcherOnChanged != null)
                        {
                            Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(
                                h => fileSystemWatcher.Changed += h,
                                h => fileSystemWatcher.Changed -= h).
                            Window(config.ExcludeDuplicateEventsWindowTime).
                            SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
                            Subscribe(pattern => { lock (_watchers) { watcherOnChanged(pattern.Sender, pattern.EventArgs); } });
                        }

                        if (watcherOnCreated != null)
                        {
                            Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(
                                h => { fileSystemWatcher.Created += h; fileSystemWatcher.Changed += h; },
                                h => { fileSystemWatcher.Created -= h; fileSystemWatcher.Changed += h; }).
                            Window(config.ExcludeDuplicateEventsWindowTime).
                            SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
                            Subscribe(pattern => { lock (_watchers) { watcherOnCreated(pattern.Sender, pattern.EventArgs); } });
                        }

                        if (watcherOnRenamed != null)
                        {
                            Observable.FromEventPattern <RenamedEventHandler, RenamedEventArgs>(
                                h => fileSystemWatcher.Renamed += h,
                                h => fileSystemWatcher.Renamed -= h).
                            Window(config.ExcludeDuplicateEventsWindowTime).
                            SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
                            Subscribe(pattern => { lock (_watchers) { watcherOnRenamed(pattern.Sender, pattern.EventArgs); } });
                        }

                        if (watcherOnDeleted != null)
                        {
                            Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(
                                h => fileSystemWatcher.Deleted += h,
                                h => fileSystemWatcher.Deleted -= h).
                            Window(config.ExcludeDuplicateEventsWindowTime).
                            SelectMany(x => x.Distinct(z => z.EventArgs.FullPath)).
                            Subscribe(pattern => { lock (_watchers) { watcherOnDeleted(pattern.Sender, pattern.EventArgs); } });
                        }
                    }
                    else
                    {
                        if (watcherOnChanged != null)
                        {
                            fileSystemWatcher.Changed += watcherOnChanged;
                        }
                        if (watcherOnCreated != null)
                        {
                            fileSystemWatcher.Created += watcherOnCreated;
                        }
                        if (watcherOnRenamed != null)
                        {
                            fileSystemWatcher.Renamed += watcherOnRenamed;
                        }
                        if (watcherOnDeleted != null)
                        {
                            fileSystemWatcher.Deleted += watcherOnDeleted;
                        }
                    }

                    _watchers.Add(fileSystemWatcher);

                    log.Info($"[Topshelf.FileSystemWatcher] configured to listen for events in {config.Path}");

                    //foreach (System.IO.FileSystemWatcher watcher in _watchers)
                    //{
                    //    watcher.EnableRaisingEvents = true;
                    //}

                    //log.Info("[Topshelf.FileSystemWatcher] listening for events");
                }
            });
        }
Пример #12
0
        public static void Configuration(ServiceConfigurator <ValidationService> config)
        {
            IKernel kernel = null;

            IDisposable webapiApp = null;

            config.ConstructUsing(() =>
            {
                return(new ValidationService());
            });

            config.BeforeStartingService(h =>
            {
                h.RequestAdditionalTime(ServerSettings.AdditionalStartupTime);

                kernel = ConfigModule.GetKernel();

                log.Info("{0} Service Started", ServiceName);
            });

            config.WhenStarted(s =>
            {
                //configuration for hangfire server.
                //tells it to use in memory storage instead of having to have a SQL backend
                Hangfire.GlobalConfiguration.Configuration.UseMemoryStorage();

                // tells hangfire which IoC to use when newing up jobs.
                Hangfire.GlobalConfiguration.Configuration.UseNinjectActivator(kernel);

                RunValidationServer(kernel);

                webapiApp = WebApp.Start(ServerSettings.WebAPIUrl, builder =>
                {
                    kernel.Get <ValidationService>().Configuration(builder);
                });
            });

            config.AfterStartingService(() =>
            {
#if DEBUG
#endif
            });

            config.WhenStopped(s =>
            {
                if (kernel != null)
                {
                    var busCleanup = kernel.Get <IBusCleanup>();
                    busCleanup.StopAllBuses();

                    log.Info("{0} Service Stopped - bus cleanup and kernel disposed", ServiceName);
                }

                //In theory, IBusCleanup should allow notifications to be sent before an app closes down.
                //However, in this case more time was required.
                //TODO - verify not needed System.Threading.Thread.Sleep(500);

                log.Info("{0} Service Stopped", ServiceName);

                webapiApp.Dispose();

                kernel.Dispose();
            });
        }