Exemplo n.º 1
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);
        }
Exemplo n.º 2
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));
            }
        }
Exemplo n.º 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());
            }
        }
Exemplo n.º 4
0
        public static void WhenStartedAsLeader <T>(
            this ServiceConfigurator <T> configurator, Action <LeaderConfigurationBuilder <T> > builder) where T : class
        {
            if (configurator == null)
            {
                throw new ArgumentNullException(nameof(configurator));
            }

            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            LeaderConfiguration <T> leaderConfiguration = null;

            configurator.BeforeStoppingService(async() =>
            {
                try
                {
                    leaderConfiguration?.ServiceIsStopping.Cancel();
                }
                catch (TaskCanceledException) { }

                if (leaderConfiguration != null)
                {
                    await leaderConfiguration.LeaseManager.ReleaseLease(leaderConfiguration.NodeId);
                }
            });

            configurator.WhenStarted(async service =>
            {
                if (leaderConfiguration == null)
                {
                    var configurationBuilder = new LeaderConfigurationBuilder <T>();

                    builder(configurationBuilder);

                    if (!configurationBuilder.ServiceStoppingTokenIsSet)
                    {
                        var serviceStoppingTokenSource = new CancellationTokenSource();
                        configurationBuilder.WhenStopping(serviceStoppingTokenSource);
                    }

                    leaderConfiguration = configurationBuilder.Build();
                }

                try
                {
                    var worker = new Runner <T>(service, leaderConfiguration);
                    await worker.Start();
                }
                catch (TaskCanceledException)
                {
                    // TaskCanceledException bubbles up if the service stopping cancellation token is set
                    // so we swallow the exception so that the Topshelf OnException handler doesn't see it
                }
            });
        }
        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...");
                });
            }
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 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 BeforeStoppingService <T>(ServiceConfigurator <T> configurator, LogWriter log, FileSystemEventHandler watcherOnChanged) where T : class
 {
     configurator.BeforeStoppingService(() =>
     {
         if (_watchers != null && _watchers.Any())
         {
             foreach (System.IO.FileSystemWatcher fileSystemWatcher in _watchers)
             {
                 fileSystemWatcher.EnableRaisingEvents = false;
                 fileSystemWatcher.Changed            -= watcherOnChanged;
                 fileSystemWatcher.Created            -= watcherOnChanged;
                 fileSystemWatcher.Deleted            -= watcherOnChanged;
                 fileSystemWatcher.Dispose();
                 log.Info("[Topshelf.FileSystemWatcher] Unsubscribed for FileSystemChange events");
             }
         }
     });
 }
Exemplo n.º 9
0
        public static ServiceConfigurator <T> WithNancyEndpoint <T>(this ServiceConfigurator <T> configurator, HostConfigurator hostconfigurator, Action <NancyServiceConfiguration> nancyConfigurator) where T : class
        {
            var nancyServiceConfiguration = new NancyServiceConfiguration();

            nancyConfigurator(nancyServiceConfiguration);

            var nancyService = new NancyService();

            nancyService.Configure(nancyServiceConfiguration);

            configurator.AfterStartingService(_ => nancyService.Start());

            configurator.BeforeStoppingService(_ => nancyService.Stop());

            hostconfigurator.BeforeInstall(_ => nancyService.BeforeInstall());

            hostconfigurator.BeforeUninstall(nancyService.BeforeUninstall);

            return(configurator);
        }
Exemplo n.º 10
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...");
                });
            }
        }