public void Start() { WebApp.Start<StartupBootstrapper>(url); this.Info(() => "Started Keep-Alive Service"); _server = new BackgroundJobServer(); var container = new WindsorContainer(); container.Register(Component.For<IApiClient>().ImplementedBy<ApiClient>()); container.Register(Component.For<HealthCheck>()); container.Register(Component.For<LoginCheck>()); container.Register(Component.For<PackageCheck>()); JobActivator.Current = new WindsorJobActivator(container.Kernel); RecurringJob.AddOrUpdate<HealthCheck>("DataPlatform HealthCheck", x => x.PingDataPlatform(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local); RecurringJob.AddOrUpdate<LoginCheck>("DataPlatform Mobile LoginCheck", x => x.MobileLogin(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local); RecurringJob.AddOrUpdate<LoginCheck>("DataPlatform API LoginCheck", x => x.ApiLogin(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local); RecurringJob.AddOrUpdate<PackageCheck>("DataPlatform API PackageCheck", x => x.InvokePackage(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local); Console.WriteLine("\r"); Console.WriteLine("Running on {0}", url); Console.WriteLine("\r\n"); Console.WriteLine("*----------------------------------------------------------------------------*"); Console.WriteLine("127.0.0.1 " + url + " <-- Required Hosts Entry!"); Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine("\r"); Console.WriteLine("Press Ctrl + c to exit"); }
public static IAppBuilder UseHangfireServer( [NotNull] this IAppBuilder builder, [NotNull] BackgroundJobServerOptions options, [NotNull] JobStorage storage) { if (builder == null) throw new ArgumentNullException("builder"); if (options == null) throw new ArgumentNullException("options"); if (storage == null) throw new ArgumentNullException("storage"); var server = new BackgroundJobServer(options, storage); Servers.Add(server); var context = new OwinContext(builder.Properties); var token = context.Get<CancellationToken>("host.OnAppDisposing"); if (token == default(CancellationToken)) { // https://github.com/owin/owin/issues/27 token = context.Get<CancellationToken>("server.OnDispose"); } if (token == default(CancellationToken)) { throw new InvalidOperationException("Current OWIN environment does not contain an instance of the `CancellationToken` class under `host.OnAppDisposing` key."); } token.Register(server.Dispose); return builder; }
public void Start() { lock (_lockObject) { if (_started) return; _started = true; HostingEnvironment.RegisterObject(this); var hfConfiguration = Container.Resolve<IHangfireConfiguration>(); var queueConfiguration = Container.Resolve<IQueueingConfiguration>(); string orderedQueue = queueConfiguration.OrderedCommandQueue; string unorderedQueue = queueConfiguration.UnorderedCommandQueue; GlobalConfiguration.Configuration.UseAutofacActivator(Container); GlobalConfiguration.Configuration.UseSqlServerStorage(hfConfiguration.ConnectionString) .UseMsmqQueues(queueConfiguration.OrderedCommandQueue, Constants.OrderedQueueName) .UseMsmqQueues(queueConfiguration.UnorderedCommandQueue, Constants.UnorderedQueueName); var unorderedOptions = SetupQueue(unorderedQueue, Constants.UnorderedQueueName); _unorderedJobServer = new BackgroundJobServer(unorderedOptions); var orderedOptions = SetupQueue(orderedQueue, Constants.OrderedQueueName); _orderedJobServer = new BackgroundJobServer(orderedOptions); } }
public void Start() { lock (this.lockObject) { if (this.started) { return; } this.started = true; HostingEnvironment.RegisterObject(this); GlobalConfiguration.Configuration.UseSqlServerStorage( DbAccess.ConnectionStringName //,new SqlServerStorageOptions() //{ //} ); // Specify other options here GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 }); //var server = new BackgroundJobServerOptions() //{ //}; this.backgroundJobServer = new BackgroundJobServer(); } }
private void ConfigureJobManagement() { GlobalConfiguration.Configuration.UseSqlServerStorage( @"Server=.\sqlexpress; Database=CyrusMicroSvcHangfire; Integrated Security=SSPI;"); const string baseAddress = "http://localhost:9000/"; // hangire storage config must be done before spinning up web instance _webApp = WebApp.Start<Startup>(baseAddress); _server = new BackgroundJobServer(); }
protected override void OnStart(string[] args) { string state = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "启动"; WriteLog(state); var options = new BackgroundJobServerOptions { Queues = new[] { "accordatapush" } }; _server = new BackgroundJobServer(options); }
public void Start() { lock (_lockObject) { if (_started) return; _started = true; HostingEnvironment.RegisterObject(this); GlobalConfiguration.Configuration .UseSqlServerStorage("Data Source=.;Initial Catalog=GalaxyStorm;Integrated Security=True"); _backgroundJobServer = new BackgroundJobServer(); } }
public void Start() { lock (_lockObject) { if (_started) return; _started = true; HostingEnvironment.RegisterObject(this); GlobalConfiguration.Configuration .UseSqlServerStorage("DbConnection"); // Specify other options here _backgroundJobServer = new BackgroundJobServer(); } }
public static IApplicationBuilder UseHangfireServer( [NotNull] this IApplicationBuilder builder, [NotNull] BackgroundJobServerOptions options, [NotNull] JobStorage storage) { if (builder == null) throw new ArgumentNullException("builder"); if (options == null) throw new ArgumentNullException("options"); if (storage == null) throw new ArgumentNullException("storage"); var server = new BackgroundJobServer(options, storage); var lifetime = builder.ApplicationServices.GetRequiredService<IApplicationLifetime>(); lifetime.ApplicationStopped.Register(server.Dispose); return builder; }
protected void Application_Start() { System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); AreaRegistration.RegisterAllAreas(); BundleConfig.RegisterBundles(BundleTable.Bundles); this.MonitorProfiler(); // 要在 DbContext 之前初始化 BootStrapper.Start(); // Start Job // Todo: Pack the job configuration to a package. GlobalConfiguration.Configuration.UseSqlServerStorage(GetRealDbConnectionName("rms")); _backgroundJobServer = new BackgroundJobServer(); Client.Jobs.JobClient.Start(); }
public static void Main() { // you can use Raven Storage and specify the connection string and database name GlobalConfiguration.Configuration .UseColouredConsoleLogProvider() .UseRavenStorage("http://localhost:8080", "hangfire", "apikeytest"); // you can use Raven Embedded Storage which runs in memory! //GlobalConfiguration.Configuration // .UseColouredConsoleLogProvider() // .UseEmbeddedRavenStorage(); //you have to create an instance of background job server at least once for background jobs to run var client = new BackgroundJobServer(); //BackgroundJob.Enqueue(() => Console.WriteLine("Background Job: Hello, world!")); BackgroundJob.Enqueue(() => test()); //RecurringJob.AddOrUpdate(() => test(), Cron.Minutely); Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); }
static void Main(string[] args) { XmlConfigurator.Configure(); //only once _log.Debug("Application is starting"); if (args.Length > 0) { _storage = new SqlServerStorage(@"Data Source=.;Initial Catalog=SpriteHangFire;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False"); var options = new BackgroundJobServerOptions(); var server = new BackgroundJobServer(options, _storage); server.Start(); Console.WriteLine("Hangfire Server started. Press any key to exit..."); var input = Console.ReadKey(); HandleInput(input); //using () //{ // server.Start(); } else { _log.Info("application launched without arguments"); throw new NullReferenceException("kkkkkkjkljfkldsjfkl"); //FileInfo f = new FileInfo(); File.Create(string.Format(@"C:\TFSDATA\KissTheFuture\Trunk\shopping.lacage.be\shoppingconsole.lacage.be\bin\Debug\{0}.txt", Guid.NewGuid())); Thread.Sleep(5000); } //c.Schedule(() => MyJob.DoSomething(), TimeSpan.FromMinutes(10)); //Console.ReadKey(); //} }
public static IApplicationBuilder UseHangfireServer( [NotNull] this IApplicationBuilder app, [CanBeNull] BackgroundJobServerOptions options = null, [CanBeNull] IEnumerable<IBackgroundProcess> additionalProcesses = null, [CanBeNull] JobStorage storage = null) { if (app == null) throw new ArgumentNullException(nameof(app)); ThrowIfNotConfigured(app); var services = app.ApplicationServices; var lifetime = services.GetRequiredService<IApplicationLifetime>(); storage = storage ?? services.GetRequiredService<JobStorage>(); options = options ?? services.GetService<BackgroundJobServerOptions>() ?? new BackgroundJobServerOptions(); additionalProcesses = additionalProcesses ?? services.GetServices<IBackgroundProcess>(); var server = new BackgroundJobServer(options, storage, additionalProcesses); lifetime.ApplicationStopping.Register(() => server.SendStop()); lifetime.ApplicationStopped.Register(() => server.Dispose()); return app; }
/// <summary> /// Starts a new instance of the <see cref="BackgroundJobServer"/> class with /// the given arguments, and registers its disposal on application shutdown. /// </summary> /// /// <param name="builder">OWIN application builder.</param> /// <param name="storage">Storage to use by background job server.</param> /// <param name="options">Options for background job server.</param> /// <param name="additionalProcesses">Collection of additional background processes.</param> /// /// <exception cref="ArgumentNullException"><paramref name="builder"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="storage"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="additionalProcesses"/> is null.</exception> /// <exception cref="InvalidOperationException"> /// OWIN environment does not contain the application shutdown cancellation token. /// </exception> /// /// <remarks> /// Please see <see cref="AppBuilderExtensions"/> for details and examples. /// </remarks> public static IAppBuilder UseHangfireServer( [NotNull] this IAppBuilder builder, [NotNull] JobStorage storage, [NotNull] BackgroundJobServerOptions options, [NotNull] params IBackgroundProcess[] additionalProcesses) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (storage == null) throw new ArgumentNullException(nameof(storage)); if (options == null) throw new ArgumentNullException(nameof(options)); if (additionalProcesses == null) throw new ArgumentNullException(nameof(additionalProcesses)); var server = new BackgroundJobServer(options, storage, additionalProcesses); Servers.Add(server); var context = new OwinContext(builder.Properties); var token = context.Get<CancellationToken>("host.OnAppDisposing"); if (token == default(CancellationToken)) { // https://github.com/owin/owin/issues/27 token = context.Get<CancellationToken>("server.OnDispose"); } if (token == default(CancellationToken)) { throw new InvalidOperationException( "Current OWIN environment does not contain an instance of the `CancellationToken` class neither under `host.OnAppDisposing`, nor `server.OnDispose` key.\r\n" + "Please use another OWIN host or create an instance of the `BackgroundJobServer` class manually."); } token.Register(server.Dispose); return builder; }
public static void Main() { LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter( LogLevel.Info, false, false, true, ""); var sqlServerStorage = new SqlServerStorage( @"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;"); sqlServerStorage.UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical"); JobStorage.Current = sqlServerStorage; //new RedisStorage("localhost:6379", 3); RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely); RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), Cron.Hourly); var options = new BackgroundJobServerOptions { Queues = new[] { "critical", "default" } }; using (var server = new BackgroundJobServer(options)) { var count = 1; while (true) { var command = Console.ReadLine(); if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase)) { break; } if (command.Equals("start", StringComparison.OrdinalIgnoreCase)) { server.Start(); } if (command.StartsWith("add", StringComparison.OrdinalIgnoreCase)) { try { var workCount = int.Parse(command.Substring(4)); for (var i = 0; i < workCount; i++) { var number = i; BackgroundJob.Enqueue<Services>(x => x.Random(number)); } Console.WriteLine("Jobs enqueued."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } if (command.StartsWith("static", StringComparison.OrdinalIgnoreCase)) { try { var workCount = int.Parse(command.Substring(7)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue(() => Console.WriteLine("Hello, {0}!", "world")); } Console.WriteLine("Jobs enqueued."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } if (command.StartsWith("error", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(6)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue<Services>(x => x.Error()); } } if (command.StartsWith("args", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(5)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue<Services>(x => x.Args(Guid.NewGuid().ToString(), 14442, DateTime.UtcNow)); } } if (command.StartsWith("custom", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(7)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue<Services>(x => x.Custom( new Random().Next(), new []{ "Hello", "world!" }, new Services.CustomObject { Id = 123 }, DayOfWeek.Friday )); } } if (command.StartsWith("fullargs", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(9)); for (var i = 0; i < workCount; i++) { BackgroundJob.Enqueue<Services>(x => x.FullArgs( false, 123, 'c', DayOfWeek.Monday, "hello", new TimeSpan(12, 13, 14), new DateTime(2012, 11, 10), new Services.CustomObject { Id = 123 }, new[] { "1", "2", "3" }, new[] { 4, 5, 6 }, new long[0], null, new List<string> { "7", "8", "9" })); } } if (command.StartsWith("in", StringComparison.OrdinalIgnoreCase)) { var seconds = int.Parse(command.Substring(2)); var number = count++; BackgroundJob.Schedule<Services>(x => x.Random(number), TimeSpan.FromSeconds(seconds)); } if (command.StartsWith("cancelable", StringComparison.OrdinalIgnoreCase)) { var iterations = int.Parse(command.Substring(11)); BackgroundJob.Enqueue<Services>(x => x.Cancelable(iterations, JobCancellationToken.Null)); } if (command.StartsWith("delete", StringComparison.OrdinalIgnoreCase)) { var workCount = int.Parse(command.Substring(7)); for (var i = 0; i < workCount; i++) { var jobId = BackgroundJob.Enqueue<Services>(x => x.EmptyDefault()); BackgroundJob.Delete(jobId); } } if (command.StartsWith("fast", StringComparison.OrdinalIgnoreCase)) { try { var workCount = int.Parse(command.Substring(5)); Parallel.For(0, workCount, i => { if (i % 2 == 0) { BackgroundJob.Enqueue<Services>(x => x.EmptyCritical()); } else { BackgroundJob.Enqueue<Services>(x => x.EmptyDefault()); } }); Console.WriteLine("Jobs enqueued."); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); }
public void Start() { WebApp.Start<Startup>(url); // HangFire Instantiation _server = new BackgroundJobServer(); // Wire-up existing jobs created var stageBillRun = new BillingMessage() { RunType = "Stage", Schedule = null }; var finalBillRun = new BillingMessage() { RunType = "Final", Schedule = null }; var prebillCacheRun = new BillCacheMessage { BillingType = typeof(PreBilling), Command = BillingCacheCommand.Reload }; var stagebillCacheRun = new BillCacheMessage { BillingType = typeof(StageBilling), Command = BillingCacheCommand.Reload }; var finalbillCacheRun = new BillCacheMessage { BillingType = typeof(FinalBilling), Command = BillingCacheCommand.Reload }; using (var job = JobStorage.Current.GetConnection()) { foreach (var recurringJob in job.GetRecurringJobs()) { if (recurringJob.Id.Contains("StageBilling Run")) RecurringJob.AddOrUpdate<MessageSchedule>(recurringJob.Id, x => x.Send(stageBillRun), recurringJob.Cron, TimeZoneInfo.Local); if (recurringJob.Id.Contains("FinalBilling Run")) RecurringJob.AddOrUpdate<MessageSchedule>(recurringJob.Id, x => x.Send(finalBillRun), recurringJob.Cron, TimeZoneInfo.Local); if (recurringJob.Id.Contains("PreBilling Cache Reload")) RecurringJob.AddOrUpdate<CacheSchedule>(recurringJob.Id, x => x.Send(prebillCacheRun), recurringJob.Cron, TimeZoneInfo.Local); if (recurringJob.Id.Contains("StageBilling Cache Reload")) RecurringJob.AddOrUpdate<CacheSchedule>(recurringJob.Id, x => x.Send(stagebillCacheRun), recurringJob.Cron, TimeZoneInfo.Local); if (recurringJob.Id.Contains("FinalBilling Cache Reload")) RecurringJob.AddOrUpdate<CacheSchedule>(recurringJob.Id, x => x.Send(finalbillCacheRun), recurringJob.Cron, TimeZoneInfo.Local); } } RecurringJob.AddOrUpdate<EmailSchedule>("Monthly StageBilling Notification", x => x.SendStageBillingNotification(), "0 8 26 * *", TimeZoneInfo.Local); //RecurringJob.AddOrUpdate<CleanupSchedule>("Transaction Request Cleanup", x => x.Send(new TransactionRequestCleanupMessage()), "0 23 * * *", TimeZoneInfo.Local); Console.WriteLine("\r"); Console.WriteLine("Running on {0}", url); Console.WriteLine("\r\n"); Console.WriteLine("*----------------------------------------------------------------------------*"); Console.WriteLine("127.0.0.1 " + url + " <-- Required Hosts Entry!"); Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine("\r"); }
static JobSchedulerConfig() { _backgroundJobServer = new BackgroundJobServer(); }