private static void AfterStartingService <T>(ServiceConfigurator <T> configurator, IEnumerable <FileSystemWatcherConfigurator.DirectoryConfiguration> configs, LogWriter log, Action <TopshelfFileSystemEventArgs> fileSystemChanged) where T : class { configurator.AfterStartingService(() => { foreach (FileSystemWatcherConfigurator.DirectoryConfiguration config in configs) { if (config.GetInitialStateEvent) { log.Info("[Topshelf.FileSystemWatcher] Checking for InitialState Events"); string[] paths; if (!string.IsNullOrWhiteSpace(config.FileFilter)) { paths = Directory.GetFiles(config.Path, config.FileFilter); } else { paths = Directory.GetFiles(config.Path); } if (paths.Any()) { foreach (string path in paths) { fileSystemChanged(FileSystemEventFactory.CreateCurrentStateFileSystemEvent(Path.GetDirectoryName(path), Path.GetFileName(path))); } } } } }); }
public AuthenticationService(ServiceConfigurator serviceConfigurator) { serviceConfigurator.Register(_serviceCollection); _service = _serviceCollection.BuildServiceProvider(); _client = _service.GetRequiredService <IRestClient>(); _client.BaseUrl = Config.GetBaseUrl(); }
/// <summary> /// Добавляет в конфигуратор Quartz задание по расписанию для парсинга album-info.ru. /// </summary> /// <param name="serviceConfigurator">Конфигуратор Quartz.</param> /// <param name="kernel">DI контейнер</param> private static void AlbumInfoParseProcess( ServiceConfigurator <TopshelfService> serviceConfigurator, IKernel kernel) { var resourceRepository = kernel.Get <IBaseRepository <ResourceEntity> >(); var resource = resourceRepository .Queryable().First(r => r.Name.Equals(Resources.AlbumInfoSettings)); var albumInfoParseIsSwitchOn = resource.ParseIsSwitchOn; var albumInfoParsingPeriodInMinutes = resource.ParsePeriodInMinutes; if (!albumInfoParseIsSwitchOn) { return; } ITrigger AlbumInfoParseTrigger() => TriggerBuilder.Create() .WithSimpleSchedule(builder => builder.WithIntervalInMinutes(albumInfoParsingPeriodInMinutes) .WithMisfireHandlingInstructionIgnoreMisfires() .RepeatForever()) .Build(); IJobDetail albumInfoParseTriggerJob = JobBuilder.Create <AlbumInfoParseJob>().Build(); albumInfoParseTriggerJob.JobDataMap.Put(CommonHelper.ContainerKey, kernel); // Запускает парсер album-info.ru serviceConfigurator.ScheduleQuartzJob(jobConfigurator => jobConfigurator .WithJob(() => albumInfoParseTriggerJob) .AddTrigger(AlbumInfoParseTrigger)); }
public static int Main(string[] args) { { var exitCode = HostFactory.Run(c => { c.Service <Service>(service => { c.SetServiceName(ServiceName); c.SetDisplayName(DisplayName); c.SetDescription(ServiceDescription); c.EnablePauseAndContinue(); c.EnableShutdown(); c.StartAutomatically(); c.RunAsLocalSystem(); ServiceConfigurator <Service> s = service; s.ConstructUsing(() => new Service()); s.WhenStarted(a => a.Start()); s.WhenStopped(a => a.Stop()); }); }); return((int)exitCode); } }
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)); } }
private static void Callback(ServiceConfigurator <MyActorService> actorService) { actorService.ConstructUsing(n => new MyActorService()); actorService.WhenStarted(service => service.Start()); actorService.WhenStopped(service => service.Stop()); //continue and restart directives are also available }
static void ConfigureScheduler(ServiceConfigurator <ServiceCore> svc) { svc.ScheduleQuartzJob(q => { //ClearUrlAccessedLog q.WithJob(JobBuilder.Create <ClearUrlAccessedLogJob>() .WithIdentity("ClearUrlAccessedLog", "BackgroundJob") .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever(24)).Build()); }, true); svc.ScheduleQuartzJob(q => { //SendMessageJob q.WithJob(JobBuilder.Create <SendMessageJob>() .WithIdentity("SendMessageJob", "BackgroundJob") .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForever(30)).Build()); }, true); svc.ScheduleQuartzJob(q => { //PMJob q.WithJob(JobBuilder.Create <PMJob>() .WithIdentity("PMJob", "BackgroundJob") .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForever(30)).Build()); }, true); }
public void EstablishContext() { using (var startEvent = new ManualResetEvent(false)) { _srv = new TestService(); _channelAdaptor = new ChannelAdapter(); _hostChannel = WellknownAddresses.GetServiceCoordinatorHost(_channelAdaptor); using (_channelAdaptor.Connect(config => config.AddConsumerOf<ServiceStarted>().UsingConsumer(msg => startEvent.Set()))) { ServiceConfigurator<TestService> c = new ServiceConfigurator<TestService>(); c.WhenStarted(s => s.Start()); c.WhenStopped(s => s.Stop()); c.WhenPaused(s => { _wasPaused = true; }); c.WhenContinued(s => { _wasContinued = true; }); c.HowToBuildService(name => _srv); _serviceController = c.Create(WellknownAddresses.GetServiceCoordinatorProxy()); _serviceController.Start(); startEvent.WaitOne(5.Seconds()); _serviceController.State.ShouldEqual(ServiceState.Started); } } }
public static ServiceConfigurator <T> UseQuartzNinject <T>(this ServiceConfigurator <T> configurator) where T : class { SetupNinject(); return(configurator); }
public static void InitSchedule(ServiceConfigurator <ServiceRunner> svc) { svc.UsingQuartzJobFactory(Container.Resolve <IJobFactory>); InitQuartzJob(); foreach (var job in JobList) { svc.ScheduleQuartzJob(q => { q.WithJob(JobBuilder.Create <ReportAutoGenerateJob>() .WithIdentity(job.Name, AppSettings.JobGroupName) .UsingJobData("JobEntity", JsonConvert.SerializeObject(job)) .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithIdentity($"{job.Name}_trigger", AppSettings.JobGroupName) .WithCronSchedule(job.CornLike) .Build()); CommHelper.AppLogger.InfoFormat("任务 {0} 已完成调度设置", job.Name); }); } CommHelper.AppLogger.Info("调度任务 初始化完毕"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers(); ServiceConfigurator.RegisterServices(services, Configuration.GetConnectionString("AppDbContext")); }
public static ServiceConfigurator <T> UseQuartzStructureMap <T>(this ServiceConfigurator <T> configurator) where T : class { SetupStructureMap(); return(configurator); }
private static IServiceProvider CreateServiceContainer(IConfiguration configuration) { var serviceCollection = new ServiceCollection(); serviceCollection.Configure <NotionVisualizerOptions>(o => configuration.GetSection(nameof(NotionVisualizer)).Bind(o)); serviceCollection.Configure <CytoscapeGeneratorOptions>(o => configuration.GetSection(nameof(CytoscapeGenerator)).Bind(o)); serviceCollection.Configure <ExcelGeneratorOptions>(o => configuration.GetSection(nameof(ExcelGenerator)).Bind(o)); serviceCollection.Configure <NotionClientOptions>(o => configuration.GetSection(nameof(NotionClient)).Bind(o)); serviceCollection.Configure <RestClientOptions>(o => configuration.GetSection(nameof(RestClient)).Bind(o)); serviceCollection.AddLogging(loggingBuilder => { loggingBuilder .AddConsole() .AddConfiguration(configuration.GetSection("Logging")); }); serviceCollection.AddTransient <IRestClient, RestClient>(); ServiceConfigurator.Configure(serviceCollection); serviceCollection.AddTransient <INotionClient, NotionClient>(); serviceCollection.AddTransient <IGenerator, CytoscapeGenerator>(); serviceCollection.AddTransient <IGenerator, ExcelGenerator>(); serviceCollection.AddTransient <Visualizer>(); return(serviceCollection.BuildServiceProvider()); }
public static ServiceConfigurator <T> UsingQuartzJobFactory <T, TJobFactory>(this ServiceConfigurator <T> configurator, Func <TJobFactory> jobFactory) where T : class where TJobFactory : IJobFactory { JobFactory = jobFactory(); return(configurator); }
public void Service(Action <ServiceConfigurator <SERVICE> > serviceConfigAction) { if (serviceConfigAction == null) { throw new ArgumentNullException(nameof(serviceConfigAction)); } try { var serviceConfig = new ServiceConfigurator <SERVICE>(HostConfiguration); serviceConfigAction(serviceConfig); if (HostConfiguration.ServiceFactory == null) { throw new ArgumentException("It's necessary to configure action that creates the service", nameof(HostConfiguration.ServiceFactory)); } if (HostConfiguration.OnServiceStart == null) { throw new ArgumentException("It's necessary to configure action that is called when the service starts", nameof(HostConfiguration.OnServiceStart)); } } catch (Exception e) { throw new ArgumentException("Configuring the service throws an exception", e); } }
public static void Schedule(IContainer container, ServiceConfigurator <JobService> svc) { try { svc.UsingQuartzJobFactory(() => container.Resolve <IJobFactory>()); } catch (Exception) { throw; } foreach (var job in JobList) { svc.ScheduleQuartzJob(q => { q.WithJob(JobBuilder.Create(Type.GetType(JobNamespceFormat.Fmt(job.Name))) .WithIdentity(job.Name, ServiceName) .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithCronSchedule(job.Cron) .Build()); log.InfoFormat("任务 {0} 已完成调度设置", JobNamespceFormat.Fmt(job.Name)); }); } }
public static void ActivateNetCoreDi(ServiceConfigurator configure) { var sc = ServiceCollection; configure.Invoke(sc); _sp = sc.BuildServiceProvider(); }
/// <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); }
public static ServiceConfigurator <T> ConstructUsing <T>(this ServiceConfigurator <T> configurator, Func <T> factory) where T : class { configurator.ConstructUsing((d, name, coordinator) => factory()); return(configurator); }
static int Main(string[] args) { try { var exitCode = HostFactory.Run(c => { c.Service <DummyRigService>(service => { ServiceConfigurator <DummyRigService> s = service; s.ConstructUsing(() => new DummyRigService()); s.WhenStarted(a => a.Start()); s.WhenStopped(a => a.Stop()); }); c.SetServiceName("DummyRigHamBus"); c.SetDisplayName("DummyRig HamBus server"); c.SetDescription("Web server for DummyRig and hambus"); }); return((int)exitCode); } catch (Exception e) { Console.WriteLine(e.Message); if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); Console.WriteLine("\n\nCould not open COM object! Exiting"); return(-1); } } return(0); }
public static ServiceConfigurator <T> UseQuartzStructureMap <T>(this ServiceConfigurator <T> configurator, bool withNestedContainers = true) where T : class { SetupStructureMap(withNestedContainers); return(configurator); }
public static ServiceConfigurator <T> WhenFileSystemDeleted <T>(this ServiceConfigurator <T> configurator, Action <FileSystemWatcherConfigurator> fileSystemWatcherConfigurator, Action <TopshelfFileSystemEventArgs> fileSystemDeleted) where T : class { return(WhenFileSystemChanged(configurator, fileSystemWatcherConfigurator, null, null, fileSystemDeleted, fileSystemDeleted)); }
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()); } }
public ServiceConfiguratorImpl(ServiceConfigurator <TService> configurator) { _configurator = configurator; _configurator.ConstructUsing((name, coordinator) => FastActivator <TService> .Create()); _configurator.SetServiceName("{0}/{1}".FormatWith(typeof(TService).Name, Guid.NewGuid())); }
protected override void OnAfterInstall(IDictionary savedState) { ServiceConfigurator.SetRecoveryOptions(this.serviceInstaller.ServiceName); using (ServiceController pc = new ServiceController(this.serviceInstaller.ServiceName)) { pc.Start(); } }
public void ConfigureService(ServiceConfigurator <IService> configurator) { configurator.ConstructUsing(BuildService); configurator.WhenStarted((service, control) => service.OnStart(control)); configurator.WhenStopped((service, control) => service.OnStop(control)); }
/// <summary> /// Bind Quartz to Topshelf service configurator and Autofac. /// </summary> /// <param name="configurator">Topshelf service configurator.</param> /// <param name="lifetimeScope">Autofac lifetime scope.</param> /// <typeparam name="T">Type of host.</typeparam> /// <returns>Service configurator for Topshelf.</returns> public static ServiceConfigurator <T> UseQuartzAutofac <T>(this ServiceConfigurator <T> configurator, ILifetimeScope lifetimeScope) where T : class { _ = lifetimeScope ?? throw new ArgumentNullException(nameof(lifetimeScope)); _ = configurator ?? throw new ArgumentNullException(nameof(configurator)); SetupAutofac(lifetimeScope); return(configurator); }
protected override void OnAfterInstall(System.Collections.IDictionary savedState) { ServiceConfigurator.SetRecoveryOptions(ServiceName()); using (ServiceController pc = new ServiceController(ServiceName())) { pc.Start(); } }
public void ConfigureServices(IServiceCollection services) { ServiceConfigurator.ConfigureServices(services, Configuration); services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public static ServiceConfigurator <OrleansService> ConstructUsing(this ServiceConfigurator <OrleansService> self, Action <OrleansServiceConfigurator> configure) { var configurator = new OrleansServiceConfigurator(); configure(configurator); self.ConstructUsing(() => configurator.Build()); return(self); }
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 ConfigureServiceClass(ServiceConfigurator<WindowsService> svc) { svc.ConstructUsing(name => new WindowsService()); svc.WhenStarted(es => es.Start()); svc.WhenStopped(es => es.Stop()); // use this later if/when needed // svc.WhenCustomCommandReceived() }
public void EstablishContext() { _srv = new TestService(); ServiceConfigurator<TestService> c = new ServiceConfigurator<TestService>(); c.WhenStarted(s => s.Start()); c.WhenStopped(s => s.Stop()); c.WhenPaused(s => { _wasPaused = true; }); c.WhenContinued(s => { _wasContinued = true; }); c.HowToBuildService((name)=> _srv); _serviceController = c.Create(); _serviceController.Start(); }
private static void ConfigureBackgroundJobs(ServiceConfigurator<ServiceCore> svc) { svc.UsingQuartzJobFactory(() => _container.Resolve<IJobFactory>()); svc.ScheduleQuartzJob(q => { q.WithJob(JobBuilder.Create<HeartbeatJob>() .WithIdentity("Heartbeat", "Maintenance") .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForever(2)).Build()); }); }
private static void ConfigureBackgroundJobs(ServiceConfigurator<ServiceCore> svc) { svc.UsingQuartzJobFactory(() => _container.Resolve<IJobFactory>()); var cron = ConfigurationManager.AppSettings.Get("CRON"); svc.ScheduleQuartzJob(q => { q.WithJob(JobBuilder.Create<VapoJob>() .WithIdentity("Vaporize", "Maintenance") .Build); q.AddTrigger(() => TriggerBuilder.Create() .WithCronSchedule(cron).Build()); }); }
private static void Setup(ServiceConfigurator<SubscriptionConfigurationService> serviceConfig) { var container = new ContainerBuilder() .RegisterServiceBus() .RegisterObservers(typeof(Program).Assembly) .Build(); var resolver = new Resolver(container.ResolveNamed, container.Resolve); serviceConfig.ConstructUsing( s => new SubscriptionConfigurationService(resolver, map => map.ListenTo<SimpleMessage>().Using<SimpleHandler>().WithConfiguration(new SubscriptionConfiguration("Test_1")) )); serviceConfig.WhenStarted(service => service.Start()); serviceConfig.WhenStopped(service => service.Stop()); }
private static void ConfigureService(ServiceConfigurator<BackupService> sc) { sc.ConstructUsing(() => new BackupService()); sc.WhenStarted(s => s.Start()); sc.WhenStopped(s => s.Stop()); }
public void Should_work() { var c = new ServiceConfigurator<TestService>(); c.WhenStarted(s => s.Start()); c.WhenStopped(s => s.Stop()); using (IServiceController service = c.Create(WellknownAddresses.GetServiceCoordinatorProxy())) { service.Start(); service.State .ShouldEqual(ServiceState.Started); } }
public void ConfigureBackgroundJobs(ServiceConfigurator<JobsManager> svc) { svc.UsingQuartzJobFactory(() => _container.Resolve<PollerAutofacJobFactory>()); foreach (var taskAdapter in _concreteTask) { string name = taskAdapter.Key; TaskAdapter adapter = taskAdapter.Value; string taskDescription = adapter.TaskDescription; if (adapter.IntervalInSeconds > 0) { svc.ScheduleQuartzJob( q => { q.WithJob( JobBuilder.Create<Job>().WithIdentity(name).WithDescription(taskDescription).Build); q.AddTrigger( () => TriggerBuilder.Create() .WithSchedule( SimpleScheduleBuilder.RepeatSecondlyForever(adapter.IntervalInSeconds)) .Build()); }); } else { svc.ScheduleQuartzJob( q => { q.WithJob( JobBuilder.Create<Job>().WithIdentity(name).WithDescription(taskDescription).Build); q.AddTrigger( () => TriggerBuilder.Create() .WithSimpleSchedule(s => s.RepeatForever() .WithInterval(TimeSpan.FromMilliseconds(1))) .StartNow() .Build()); }); } } }
public void Should_work() { var c = new ServiceConfigurator<TestService>(); c.WhenStarted(s => s.Start()); c.WhenStopped(s => s.Stop()); IServiceController service = c.Create(); service.Start(); service.State .ShouldEqual(ServiceState.Started); }