/// <summary> /// Tells bootstrapper to start a job server with the given /// amount of workers on application start and stop it automatically /// on application shutdown request. Global job storage is being used. /// </summary> /// <param name="configuration">Configuration</param> /// <param name="workerCount">Worker count</param> public static void UseServer( this IBootstrapperConfiguration configuration, int workerCount) { var options = new BackgroundJobServerOptions { WorkerCount = workerCount }; configuration.UseServer(() => new BackgroundJobServer(options)); }
/// <summary> /// Tells bootstrapper to start a job server with the given /// queues array on application start and stop it automatically /// on application shutdown request. Global job storage is being used. /// </summary> /// <param name="configuration">Configuration</param> /// <param name="queues">Queues to listen</param> public static void UseServer( this IBootstrapperConfiguration configuration, params string[] queues) { var options = new BackgroundJobServerOptions { Queues = queues }; configuration.UseServer(() => new BackgroundJobServer(options)); }
public BackgroundJobServerFacts() { _storage = new Mock<JobStorage>(); _options = new BackgroundJobServerOptions(); _supervisor = new Mock<IServerSupervisor>(); _serverMock = new Mock<BackgroundJobServer>(_options, _storage.Object) { CallBase = true }; _serverMock.Setup(x => x.GetBootstrapSupervisor()).Returns(_supervisor.Object); }
static void Main() { // log4net.Config.XmlConfigurator.Configure();00000000 logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Worker Host process has been started"); unityContainer = UnityConfig.Register(); UnityConfig.ConfigureDefaults(unityContainer); var storage = new SqlServerStorage("HangfireStorageDbContext"); var options = new BackgroundJobServerOptions() { WorkerCount = 10 }; UnityJobActivator unityJobActivator = new UnityJobActivator(unityContainer); GlobalConfiguration.Configuration.UseActivator(unityJobActivator); JobActivator.Current = unityJobActivator; GlobalJobFilters.Filters.Add(new ChildContainerPerJobFilterAttribute(unityJobActivator)); var server = new BackgroundJobServer(options, storage); server.Start(); Thread.Sleep(300000); server.Stop(); }
public abstract void ConfigureHangfireServer(TenantBuilderContext context, BackgroundJobServerOptions options);
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, LiveHAPIContext dbcontext, IServiceProvider serviceProvider) { bool imHapi = true; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.Use(async(context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api/")) { context.Request.Path = "/index.html"; await next(); } }); app.UseMvcWithDefaultRoute(); app.UseDefaultFiles(); app.UseStaticFiles(); Log.Debug($"database initializing..."); var bulkConfigName = Startup.Configuration["bulkConfig:name"]; var bulkConfigCode = Startup.Configuration["bulkConfig:code"]; try { DapperPlusManager.AddLicense(bulkConfigName, bulkConfigCode); if (!Z.Dapper.Plus.DapperPlusManager.ValidateLicense(out var licenseErrorMessage)) { throw new Exception(licenseErrorMessage); } } catch (Exception e) { Log.Debug($"{e}"); throw; } string herror = ""; try { EnsureMigrationOfContext <LiveHAPIContext>(serviceProvider); } catch (Exception e) { imHapi = false; Log.Error(new string('<', 30)); Log.Error($"{e}"); Log.Error(new string('>', 30)); } #region HangFire try { app.UseHangfireDashboard("/api/hangfire", new DashboardOptions() { Authorization = new[] { new CustomAuthorizeFilter() } }); var options = new BackgroundJobServerOptions { WorkerCount = 1 }; app.UseHangfireServer(options); GlobalJobFilters.Filters.Add(new ProlongExpirationTimeAttribute()); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute() { Attempts = 3 }); var defaultBatchJobRetentionPeriod = new TimeSpan(270, 0, 0, 0); //2 day retention GlobalConfiguration.Configuration.UseBatches(defaultBatchJobRetentionPeriod); } catch (Exception e) { Log.Fatal(e, "Hangfire is down !"); imHapi = false; } #endregion AutoMapper.Mapper.Initialize(cfg => { cfg.CreateMap <PracticeDTO, Practice>(); cfg.CreateMap <ClientStateInfo, ClientState>(); cfg.CreateMap <TempClientRelationship, ClientRelationship>(); cfg.CreateMap <ClientRelationship, TempClientRelationship>(); cfg.CreateMap <County, CountyInfo>(); cfg.CreateMap <SubCounty, SubCountyInfo>(); cfg.CreateMap <Category, CategoryInfo>(); cfg.CreateMap <Item, ItemInfo>(); cfg.CreateMap <CategoryItem, CategoryItemInfo>(); cfg.CreateMap <PracticeType, PracticeTypeInfo>(); cfg.CreateMap <IdentifierType, IdentifierTypeInfo>(); cfg.CreateMap <RelationshipType, RelationshipTypeInfo>(); cfg.CreateMap <KeyPop, KeyPopInfo>(); cfg.CreateMap <MaritalStatus, MaritalStatusInfo>(); cfg.CreateMap <ProviderType, ProviderTypeInfo>(); cfg.CreateMap <Action, ActionInfo>(); cfg.CreateMap <Condition, ConditionInfo>(); cfg.CreateMap <ValidatorType, ValidatorTypeInfo>(); cfg.CreateMap <CategoryItem, CategoryItemInfo>(); cfg.CreateMap <ConceptType, ConceptTypeInfo>(); cfg.CreateMap <Validator, ValidatorInfo>(); cfg.CreateMap <EncounterType, EncounterTypeInfo>(); cfg.CreateMap <SubscriberCohort, CohortInfo>(); cfg.CreateMap <Encounter, EncounterInfo>(); cfg.CreateMap <Obs, ObsInfo>(); cfg.CreateMap <ObsTestResult, ObsTestResultInfo>(); cfg.CreateMap <ObsFinalTestResult, ObsFinalTestResultInfo>(); cfg.CreateMap <ObsTraceResult, ObsTraceResultInfo>(); cfg.CreateMap <ObsLinkage, ObsLinkageInfo>(); cfg.CreateMap <ObsMemberScreening, ObsMemberScreeningInfo>(); cfg.CreateMap <ObsPartnerScreening, ObsPartnerScreeningInfo>(); cfg.CreateMap <ObsFamilyTraceResult, ObsFamilyTraceResultInfo>(); cfg.CreateMap <ObsPartnerTraceResult, ObsPartnerTraceResultInfo>(); cfg.CreateMap <ClientSummaryInfo, ClientSummary>(); int userId; cfg.CreateMap <Core.Model.People.User, UserDTO>() .ForMember(x => x.Password, o => o.MapFrom(s => s.DecryptedPassword)) .ForMember(x => x.UserId, o => o.MapFrom(s => int.TryParse(s.SourceRef, out userId) ? userId : 0)); cfg.CreateMap <Person, PersonDTO>() .ForMember(x => x.FirstName, o => o.MapFrom(s => null != s.Names.FirstOrDefault() ? s.Names.FirstOrDefault().FirstName : "")) .ForMember(x => x.MiddleName, o => o.MapFrom(s => null != s.Names.FirstOrDefault() ? s.Names.FirstOrDefault().MiddleName : "")) .ForMember(x => x.LastName, o => o.MapFrom(s => null != s.Names.FirstOrDefault() ? s.Names.FirstOrDefault().LastName : "")); cfg.CreateMap <Provider, ProviderDTO>(); cfg.CreateMap <ClientContactNetwork, ContactTreeInfo>() .ForMember(x => x.Label, o => o.MapFrom(s => s.Names)) .ForMember(x => x.Children, o => o.MapFrom(s => s.Networks)); }); Log.Debug(@" ╔═╗┌─┐┬ ┬┌─┐ ╔╦╗┌─┐┌┐ ┬ ┬ ┌─┐ ╠═╣├┤ └┬┘├─┤ ║║║│ │├┴┐│ │ ├┤ ╩ ╩└ ┴ ┴ ┴ ╩ ╩└─┘└─┘┴ ┴─┘└─┘ "); Log.Debug(""); Log.Debug(@" _ _ ____ ___ | |__ / \ | _ \_ _| | '_ \ / _ \ | |_) | | | | | |/ ___ \| __/| | |_| |_/_/ \_\_| |___| "); if (imHapi) { Log.Debug($"im hAPI !!! "); } else { Log.Error($"im NOT hAPI >*|*< "); Log.Error($"cause: {herror}"); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp) { var accessor = app.ApplicationServices.GetRequiredService <IHttpContextAccessor>(); WebHelper._httpContextAccessor = accessor; WebHelper._hostingEnvironment = app.ApplicationServices.GetRequiredService <IHostingEnvironment>(); ServiceLocator.Instance = app.ApplicationServices; app.UseStaticFiles();//使用静态文件 app.UseSession(); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Admin/Control/Error"); } app.UseMvc(routes => { routes.MapRoute( name: "Admin", template: "{area:exists}/{controller=Home}/{action=ChooseSystem}/{id?}/{extraValue?}"); routes.MapRoute( name: "DefaultIndex", template: "{area:exists}/{controller=exists}/{action=Index}/{id?}/{extraValue?}"); routes.MapRoute( "default", "{action}/{id?}/{extraValue?}", new { area = "Front", controller = "Home", action = "Index" }); }); loggerFactory.AddNLog(); //添加NLog env.ConfigureNLog("nlog.config"); //读取Nlog配置文件 //使用hangfire var jobOptions = new BackgroundJobServerOptions { Queues = new[] { "Job" }, //队列名称,只能为小写 WorkerCount = Environment.ProcessorCount * 5, //并发任务数 ServerName = "lkJob", //服务器名称 }; app.UseHangfireServer(jobOptions); var options = new DashboardOptions { Authorization = new[] { new HangfireAuthorizationFilter() } }; app.UseHangfireDashboard("/jobs", options); }
/// <summary> /// The configuration. /// </summary> /// <param name="app"> /// The app. /// </param> public void Configuration(IAppBuilder app) { var options = GetDscManagerOptions(); var httpListener = (HttpListener)app.Properties["System.Net.HttpListener"]; httpListener.AuthenticationSchemes = AuthenticationSchemes.Ntlm | AuthenticationSchemes.Anonymous; // Set up DI var containerBuilder = RegisterTypes(options); containerBuilder.RegisterInstance(options).AsImplementedInterfaces(); // Register types for components containerBuilder.RegisterNodeRepositoryTypes(options.NodeRepositoryOptions); containerBuilder.RegisterDeploymentServerTypes(options.DeploymentServerOptions); containerBuilder.RegisterReportingEndpointTypes(options.ReportingEndpointOptions); // Build container var container = containerBuilder.Build(); Container = container; // Initialize DB MigrationsContextFactory.NameOrConnectionString = "DscManager"; var logging = container.Resolve <IDscManagerLogging>(); Database.SetInitializer(new DscManagerContextInitializer(logging)); var context = container.Resolve <DscManagerContext>(); context.Database.Initialize(true); var init = container.Resolve <IDataInitializer>(); if (init.ShouldRunInitializer()) { init.Initialize(); } context.Dispose(); // Configure HangFire GlobalConfiguration.Configuration.UseSqlServerStorage("DscManager"); GlobalConfiguration.Configuration.UseAutofacActivator(container); if (options.UseJobDashboard) { app.UseHangfireDashboard(); } this.SetupDbCleanup(); if (options.UseHangfireJobServer) { var jobServerOptions = new BackgroundJobServerOptions { Queues = new[] { "mofbuilder" }, WorkerCount = options.WorkerCount }; app.UseHangfireServer(jobServerOptions); } var hangfireOptions = new BackgroundJobServerOptions { Queues = new[] { "priority", "default" }, WorkerCount = 10 }; app.UseHangfireServer(hangfireOptions); // Resolve ViewModelFactory so we have an instance container.Resolve <IViewModelFactory>(); // Set up config var config = container.Resolve <HttpConfiguration>(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); config.MessageHandlers.Add(new UrlHelperHandler(container.ComponentRegistry)); // Filters var p = container.Resolve <IEnvironmentProperties>(); if (!p.DebuggerAttached) { config.Filters.Add(new AuthorizeAttribute()); } config.MessageHandlers.Add(new AuthenticationHandler(container, container.Resolve <IDscManagerLogging>())); // Formatters config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; config.Formatters.Add(new JsonTextMediaFormatter()); // Policies config.IncludeErrorDetailPolicy = options.ErrorDetailPolicy; // Routes config.MapHttpAttributeRoutes(new CentralizedPrefixProvider("api/v{version:int}")); // Set up components app.UseNodeRepositoryComponent(container); app.UseDeploymentServerComponent(container); app.UseReportingEndpointComponent(container); app.UseCredentialRepository(options.CredentialRepositoryOptions); // Set up event infrastructure var eventHandlers = container.Resolve <IEnumerable <IDscEventHandler> >(); foreach (var handler in eventHandlers) { handler.Start(); } // Set up middleware app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); if (options.UseApi) { app.UseWebApi(config); } config.EnableCors(new EnableCorsAttribute("*", "*", "*")); config.EnsureInitialized(); container.Resolve <IDscManagerLogging>().Start(); }
//[Fact, Trait("Category", "DataGeneration")] public void Clean_Database_Filled() { var databaseName = "Mongo-Hangfire-Filled"; var context = ConnectionUtils.CreateDbContext(databaseName); // Make sure we start from scratch context.Database.Client.DropDatabase(databaseName); var storageOptions = new MongoStorageOptions { MigrationOptions = new MongoMigrationOptions { MigrationStrategy = new DropMongoMigrationStrategy(), BackupStrategy = new NoneMongoBackupStrategy() }, QueuePollInterval = TimeSpan.FromMilliseconds(500) }; var serverOptions = new BackgroundJobServerOptions { ShutdownTimeout = TimeSpan.FromSeconds(15) }; JobStorage.Current = ConnectionUtils.CreateStorage(databaseName); using (new BackgroundJobServer(serverOptions)) { // Recurring Job RecurringJob.AddOrUpdate(() => HangfireTestJobs.ExecuteRecurringJob("Recurring job"), Cron.Minutely); // Scheduled job BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteScheduledJob("Scheduled job"), TimeSpan.FromSeconds(30)); // Enqueued job BackgroundJob.Enqueue(() => HangfireTestJobs.ExecuteEnqueuedJob("Enqueued job")); // Continued job var parentId = BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteContinueWithJob("ContinueWith job", false), TimeSpan.FromSeconds(15)); BackgroundJob.ContinueWith(parentId, () => HangfireTestJobs.ExecuteContinueWithJob("ContinueWith job continued", true)); // Now the waiting game starts HangfireTestJobs.ScheduleEvent.WaitOne(); BackgroundJob.Schedule(() => HangfireTestJobs.ExecuteScheduledJob("Scheduled job (*)"), TimeSpan.FromMinutes(30)); HangfireTestJobs.ContinueWithEvent.WaitOne(); HangfireTestJobs.RecurringEvent.WaitOne(); HangfireTestJobs.EnqueueEvent.WaitOne(); BackgroundJob.Enqueue(() => HangfireTestJobs.ExecuteEnqueuedJob("Enqueued job (*)")); } // Some data are cleaned up when hangfire shuts down. // Grab a copy so we can write it back - needed for migration tests. var connection = JobStorage.Current.GetConnection(); connection.AnnounceServer("test-server", new ServerContext { WorkerCount = serverOptions.WorkerCount, Queues = serverOptions.Queues }); connection.AcquireDistributedLock("test-lock", TimeSpan.FromSeconds(30)); // Create database snapshot in zip file var schemaVersion = (int)MongoMigrationManager.RequiredSchemaVersion; using (var stream = new FileStream($@"Hangfire-Mongo-Schema-{schemaVersion:000}.zip", FileMode.Create)) { var allowedEmptyCollections = new List <string> { "hangfire.migrationLock" }; if (MongoMigrationManager.RequiredSchemaVersion >= MongoSchema.Version09 && MongoMigrationManager.RequiredSchemaVersion <= MongoSchema.Version15) { // Signal collection work was initiated in schema version 9, // and still not put to use in schema version 15. allowedEmptyCollections.Add($@"{storageOptions.Prefix}.signal"); } BackupDatabaseToStream(databaseName, stream, allowedEmptyCollections.ToArray()); } }
/// <summary> /// Initializes a new instance of the <see cref="AspNetBackgroundJobServer"/> /// class with the given options and job storage, and places it to the list /// of registered /// objects in the application. /// </summary> public AspNetBackgroundJobServer(BackgroundJobServerOptions options, JobStorage storage) : base(options, storage) { HostingEnvironment.RegisterObject(this); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { Stopwatch stopWatch = Stopwatch.StartNew(); //ServiceProvider = serviceProvider; app.UseResponseCompression(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseCors( builder => builder .WithOrigins("http://*****:*****@"initializing Database..."); EnsureMigrationOfContext <SettingsContext>(serviceProvider); EnsureMigrationOfContext <ExtractsContext>(serviceProvider); app.UseSignalR( routes => { routes.MapHub <ExtractActivity>($"/{nameof(ExtractActivity).ToLower()}"); routes.MapHub <CbsActivity>($"/{nameof(CbsActivity).ToLower()}"); routes.MapHub <HtsActivity>($"/{nameof(HtsActivity).ToLower()}"); routes.MapHub <MgsActivity>($"/{nameof(MgsActivity).ToLower()}"); routes.MapHub <DwhSendActivity>($"/{nameof(DwhSendActivity).ToLower()}"); routes.MapHub <CbsSendActivity>($"/{nameof(CbsSendActivity).ToLower()}"); routes.MapHub <HtsSendActivity>($"/{nameof(HtsSendActivity).ToLower()}"); routes.MapHub <MgsSendActivity>($"/{nameof(MgsSendActivity).ToLower()}"); } ); Mapper.Initialize(cfg => { cfg.AddDataReaderMapping(); cfg.AddProfile <TempExtractProfile>(); cfg.AddProfile <TempMasterPatientIndexProfile>(); cfg.AddProfile <EmrProfiles>(); cfg.AddProfile <TempHtsExtractProfile>(); if (null != AppFeature && AppFeature.PKV.IsValid) { cfg.AddProfile <MasterPatientIndexProfileResearch>(); } else { cfg.AddProfile <MasterPatientIndexProfile>(); } cfg.AddProfile <TempMetricExtractProfile>(); } ); DomainEvents.Init(); stopWatch.Stop(); Log.Debug(@"initializing Database [Complete]"); if (null != AppFeature) { Log.Debug(new string('=', 50)); Log.Debug("Features"); Log.Debug($" {AppFeature.PKV}"); Log.Debug(new string('=', 50)); } Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug (@" _____ _ | __ \ (_) | | | |_ ____ _ _ __ _ | | | \ \ /\ / / _` | '_ \| | | |__| |\ V V / (_| | |_) | | |_____/ \_/\_/ \__,_| .__/|_| | | |_| "); Log.Debug( @"---------------------------------------------------------------------------------------------------"); if (StartupErrors.Any()) { Log.Error(new string('*', 60)); Log.Error($"Dwapi startup FAILED, took {stopWatch.ElapsedMilliseconds} ms"); Log.Error($"Startup Failed Due to the follwing {StartupErrors.Count} ERROR(s)"); Log.Error(new string('-', 60)); StartupErrors.ForEach(Log.Error); Log.Error(new string('-', 60)); Log.Error(new string('*', 60)); } else { Log.Debug($"Dwapi started in {stopWatch.ElapsedMilliseconds} ms"); } }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime, IDistributedCache cache) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } #region 缓存 //lifetime.ApplicationStarted.Register(() => //{ // var currentTimeUTC = DateTime.UtcNow.ToString(); // byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC); // var options = new DistributedCacheEntryOptions() // .SetSlidingExpiration(TimeSpan.FromSeconds(20)); // cache.Set("cachedTimeUTC", encodedCurrentTimeUTC, options); //}); #endregion #region Swagger UI app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasisSoa API V1"); // Other c.DocumentTitle = "BasisSoa.Api 在线文档调试"; // 将swagger首页,设置成我们自定义的页面,记得这个字符串的写法:解决方案名.index.html c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("BasisSoa.Api.index.html"); }); #endregion #region WebSocket app.Map("/ApiWebSocket", NoticeHandler.Map); #endregion #region http请求认证 app.UseAuthentication(); app.UseCors("AllowAll"); app.UseHttpsRedirection(); #endregion #region 性能压缩 app.UseResponseCompression(); #endregion #region MiniProfiler请求时间性能检测框架 app.UseMiniProfiler(); app.UseStaticFiles(); #endregion #region 定时任务 Hangfire var jobOption = new BackgroundJobServerOptions { WorkerCount = 5//并发数 }; app.UseHangfireServer(jobOption); app.UseHangfireDashboard(); #endregion #region 配置静态资源 app.UseStaticFiles(new StaticFileOptions { FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(System.IO.Path.Combine(AppContext.BaseDirectory, "Uploads/HeadImage")), RequestPath = "/Uploads/HeadImage" }); #endregion app.UseMvc(); }
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("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(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { string sqlConnectionString = Configuration.GetConnectionString("HangfireConnection"); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "GetPet.Scheduler", Version = "v1" }); }); // Add Hangfire services. services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(sqlConnectionString, new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true })); var sqlStorage = new SqlServerStorage(sqlConnectionString); var options = new BackgroundJobServerOptions { ServerName = "GetPet HangFire Server", }; JobStorage.Current = sqlStorage; // Add the processing server as IHostedService services.AddHangfireServer(options => { options.ServerName = "GetPet HangFire Server"; // options.a = new[] { new DashboardNoAuthorizationFilter() }; // options.WorkerCount = 1; }); var serviceProvider = services .AddDbContext <GetPetDbContext>(options => { options.UseSqlServer(sqlConnectionString); options.EnableSensitiveDataLogging(); }) .AddAutoMapper(typeof(GetPetProfile)) .AddScoped <IPetRepository, PetRepository>() .AddScoped <IGetPetDbContextSeed, GetPetDbContextSeed>() .AddScoped <ITraitRepository, TraitRepository>() .AddScoped <ICityRepository, CityRepository>() .AddScoped <IUserRepository, UserRepository>() .AddScoped <IAnimalTypeRepository, AnimalTypeRepository>() .AddScoped <IPetHandler, PetHandler>() .AddScoped <RehovotSpaCrawler, RehovotSpaCrawler>() .AddScoped <SpcaCrawler, SpcaCrawler>() .AddScoped <RlaCrawler, RlaCrawler>() .AddScoped <JspcaCrawler, JspcaCrawler>() .AddScoped <IUserHandler, UserHandler>() .AddScoped <IUnitOfWork, UnitOfWork>() .AddScoped <IEmailHistoryRepository, EmailHistoryRepository>() .AddScoped <INotificationRepository, NotificationRepository>() .AddScoped <INotificationHandler, NotificationHandler>() .AddScoped <ITraitOptionRepository, TraitOptionRepository>() .AddScoped(sp => Configuration.GetSection("MailSettings").Get <MailSettings>()) .AddTransient <IMailHandler, MailHandler>() .AddScoped <IPetHistoryStatusRepository, PetHistoryStatusRepository>() .AddScoped <AzureBlobHelper>() .AddScoped <ImageHelper>() .AddScoped <SpcaParser>() .AddScoped <RlaParser>() .AddScoped <RehovotSpaParser>() .AddScoped <JspcaParser>(); SetBackgroundJobs(); }
static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Debug() .WriteTo.LiterateConsole() .WriteTo.RollingFile("log-{Date}.txt", LogEventLevel.Debug) .CreateLogger(); try { Log.Information("Starting JobRunner host"); var enviromentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"; var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{enviromentName}.json", true); var configuration = builder.Build(); var services = new ServiceCollection(); services.AddSingleton(p => configuration); services.AddLogging(b => b.AddSerilog()); services.AddOptions(); services.KickStart(config => config .IncludeAssemblyFor <TrainDTrainorContext>() .Data(ConfigurationServiceModule.ConfigurationKey, configuration) .Data("hostProcess", "runner") .UseAutoMapper() .UseStartupTask() ); var connectionString = configuration.GetConnectionString("TrainDTrainor"); var storageOptions = new SqlServerStorageOptions(); GlobalConfiguration.Configuration.UseSqlServerStorage(connectionString, storageOptions); var serverOptions = new BackgroundJobServerOptions(); using (var webJobHost = new WebJobHost()) using (var backgroundJobServer = new BackgroundJobServer(serverOptions)) { webJobHost.RunAndBlock(); } return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "DWAPI Central HTS API"); c.SupportedSubmitMethods(new Swashbuckle.AspNetCore.SwaggerUI.SubmitMethod[] { }); }); // app.UseHttpsRedirection(); app.UseMvc(); EnsureMigrationOfContext <HtsContext>(); Mapper.Initialize(cfg => { cfg.AddDataReaderMapping(); } ); #region HangFire try { app.UseHangfireDashboard(); var options = new BackgroundJobServerOptions { WorkerCount = 1 }; app.UseHangfireServer(options); GlobalJobFilters.Filters.Add(new ProlongExpirationTimeAttribute()); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute() { Attempts = 3 }); } catch (Exception e) { Log.Fatal(e, "Hangfire is down !"); } #endregion try { DapperPlusManager.AddLicense("1755;700-ThePalladiumGroup", "2073303b-0cfc-fbb9-d45f-1723bb282a3c"); if (!Z.Dapper.Plus.DapperPlusManager.ValidateLicense(out var licenseErrorMessage)) { throw new Exception(licenseErrorMessage); } } catch (Exception e) { Log.Debug($"{e}"); throw; } Log.Debug(@"initializing Database [Complete]"); Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug(@" ________ .__ _________ __ .__ \______ \__ _ _______ ______ |__| \_ ___ \ ____ _____/ |_____________ | | | | \ \/ \/ /\__ \ \____ \| | / \ \/_/ __ \ / \ __\_ __ \__ \ | | | ` \ / / __ \| |_> > | \ \___\ ___/| | \ | | | \// __ \| |__ /_______ /\/\_/ (____ / __/|__| /\ \______ /\___ >___| /__| |__| (____ /____/ \/ \/|__| \/ \/ \/ \/ \/ "); Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug("Dwapi Central started !"); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { GlobalConfiguration.Configuration.UseActivator(new HangfireJobActivator(serviceProvider)); JobHelper.SetSerializerSettings(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); var whenDo = app.ApplicationServices.GetRequiredService <IWhenDoEngine>(); whenDo.RegisterCommandHandler <PhilipsHueCommandHandler>("PhilipsHue"); whenDo.RegisterCommandHandler <SensorMessagePersistenceCommandHandler>("SensorMessagePersistence"); whenDo.RegisterCommandHandler <NefitHeatingCommandHandler>("NefitHeating"); JobStorage.Current = new MemoryStorage(); var options = new BackgroundJobServerOptions { WorkerCount = Environment.ProcessorCount * 3 }; app.UseHangfireServer(options); var list = new List <IDashboardAuthorizationFilter>() { new HangfireAuthFilter() }; app.UseHangfireDashboard(options: new DashboardOptions() { Authorization = list }); //TODO: Check this for authentication: https://stackoverflow.com/questions/41623551/asp-net-core-mvc-hangfire-custom-authentication if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Default}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Default", action = "Index" }); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, IHostApplicationLifetime appLifetime) { Utilities.AppServiceProvider = serviceProvider; Utilities.HostingEnvironment = env; Console.WriteLine($"GCSettings.IsServerGC:{System.Runtime.GCSettings.IsServerGC}"); Console.WriteLine($"GCSettings.LargeObjectHeapCompactionMode:{System.Runtime.GCSettings.LargeObjectHeapCompactionMode}"); Console.WriteLine($"GCSettings.LatencyMode:{System.Runtime.GCSettings.LatencyMode}"); Console.WriteLine($"GCMemoryInfo.HeapSizeBytes:{GC.GetGCMemoryInfo().HeapSizeBytes}"); Console.WriteLine($"GCMemoryInfo.HighMemoryLoadThresholdBytes:{GC.GetGCMemoryInfo().HighMemoryLoadThresholdBytes}"); Console.WriteLine($"GCMemoryInfo.TotalAvailableMemoryBytes:{GC.GetGCMemoryInfo().TotalAvailableMemoryBytes}"); Console.WriteLine($"GCMemoryInfo.MemoryLoadBytes:{GC.GetGCMemoryInfo().MemoryLoadBytes}"); Console.WriteLine($"GCMemoryInfo.FragmentedBytes:{GC.GetGCMemoryInfo().FragmentedBytes}"); app.UseMiddleware <HttpFilters.GCMiddleware>(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); var culture = CultureInfo.CreateSpecificCulture("en-US"); var dateformat = new DateTimeFormatInfo { ShortDatePattern = "MM/dd/yyyy", LongDatePattern = "MM/dd/yyyy hh:mm:ss tt" }; culture.DateTimeFormat = dateformat; CultureInfo.DefaultThreadCurrentUICulture = culture; CultureInfo.DefaultThreadCurrentCulture = culture; } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); app.UseHttpsRedirection(); } app.UseResponseCompression(); app.UseStaticFiles(); app.UseRouting(); // global cors policy app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) // allow any origin .AllowCredentials()); // allow credentials app.UseAuthentication(); app.UseAuthorization(); app.UseSession(); app.UseCookiePolicy(); //hangfire settings Hangfire.Logging.LogProvider.SetCurrentLogProvider(null); var pgoptions = new PostgreSqlStorageOptions { InvisibilityTimeout = TimeSpan.FromHours(2) // default value }; pgoptions.SchemaName = ConfigVars.Instance.herokuAddonAppName; GlobalConfiguration.Configuration.UsePostgreSqlStorage(ConfigVars.Instance.hangfireConnectionString, pgoptions); //set hangfire dashboard url app.UseHangfireDashboard("/scheduledjobs", new DashboardOptions() { Authorization = new[] { new HangFireAuthorizationFilter() }, DisplayStorageConnectionString = false }); Console.WriteLine(string.Format("Environment:{0} - ProcessorCount:{1}", (env.IsDevelopment() ? "Development" : "Production"), Environment.ProcessorCount)); //WorkerCount = Math.Min(Environment.ProcessorCount * 5, 20) var serverOptions = new BackgroundJobServerOptions() { WorkerCount = ConfigVars.Instance.deDup_workerCount, Activator = null, FilterProvider = null, ServerTimeout = TimeSpan.FromMinutes(1), ServerCheckInterval = TimeSpan.FromMinutes(1), SchedulePollingInterval = TimeSpan.FromMinutes(1), TimeZoneResolver = app.ApplicationServices.GetService <ITimeZoneResolver>(), ServerName = $"{ConfigVars.Instance.herokuAddonAppName}_{Math.Abs(Guid.NewGuid().ToInt())}", Queues = new[] { Constants.JOB_QUEUE_NAME.Trim(), "default" } }; Console.WriteLine("Production_Setup_Count:{0}", serverOptions.WorkerCount); //assign hangfire server options(background jobs) app.UseHangfireServer(serverOptions); try { //Remove Duplicte HangFire Server Console.WriteLine("Restarted sync after Heroku Dyno Restart, no action needed on your part"); var servers = JobStorage.Current.GetMonitoringApi().Servers().Where(p => p.Name.Trim().StartsWith(ConfigVars.Instance.herokuAddonAppName.Trim(), StringComparison.OrdinalIgnoreCase)).OrderByDescending(p => p.Heartbeat).ToArray(); if (servers != null && servers.Length > 0) { using (var connection = JobStorage.Current.GetConnection()) { for (int i = 0; i < servers.Length; ++i) { if (i == 0) { continue; } connection.RemoveServer(servers[i].Name); } } } } catch (Exception ex) { Console.WriteLine("Error: [0}", ex.Message); } app.Use(next => async context => { var request = context.Request; if (request.IsHttps || // Handles https straight to the server request.Headers["X-Forwarded-Proto"] == request.Scheme || // Handles an IIS or Azure passthrough request.Host.ToString().StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase) || // Ignore for localhost request.Headers["X-Forwarded-Proto"].ToString().Contains(request.Scheme)) // X-Forwarded-Proto can have multiple values if there are multiple proxies { await next(context); } else { //context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null; string newUrl = $"https://{request.Host}{request.Path}{request.QueryString}"; context.Response.Redirect(newUrl, true); } }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); ////Only one local or production //try //{ // using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) // { // serviceScope.ServiceProvider.GetService<DeDupContext>().Database.Migrate(); // } //} //catch (Exception e) //{ // var msg = e.Message; // var stacktrace = e.StackTrace; //} try { //schedule dedup process if they were not scheduled Dedup.Services.JobScheduler.Instance.ResetScheduledJobs(); } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } }
private static void Main(string[] args) { //任务系统出错的情况 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // 创建Host ,这里可以进一步简化 var host = new HostBuilder() .ConfigureHostConfiguration(builder => { builder.AddJsonFile("hosting.json", optional: true) .AddCommandLine(args) .AddEnvironmentVariables(prefix: "DOTBPE_"); }) .ConfigureAppConfiguration((hostContext, config) => { config.AddJsonFile("dotbpe.json", optional: true, reloadOnChange: true) .AddJsonFile($"dotbpe.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(prefix: "DOTBPE_"); }) .ConfigureLogging((context, builder) => { builder .AddConfiguration(context.Configuration.GetSection("Logging")) .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddFilter("Hangfire", LogLevel.Information) .AddConsole(); }) .ConfigureServices((context, services) => { string redisString = context.Configuration.GetValue <string>("Hangfire:Redis"); services.AddSingleton <IHangfireJobService, TransforHangfireJobService>(); var option = new BackgroundJobServerOptions { //wait all jobs performed when BackgroundJobServer shutdown. ShutdownTimeout = TimeSpan.FromMinutes(30), Queues = new string[] { "default", "order" }, WorkerCount = Math.Max(Environment.ProcessorCount, 20) }; services.AddSingleton(option); string prefix = context.Configuration.GetValue <string>("Hangfire:Prefix"); services.AddHangfire(configuration => { configuration.UseRedisStorage(redisString, new Redis.RedisStorageOptions() { Prefix = prefix }); //configuration.UseColouredConsoleLogProvider(); configuration.UseConsole(); }); //内部服务地址,也可以使用服务发现的方式,这里使用本地配置 services.Configure <RemoteServicesOption>(context.Configuration.GetSection("remoteServices")); //默认链接数 services.Configure <RpcClientOption>(x => x.MultiplexCount = 5); //让服务拥有调用DotBPE接口的能力 services.AddGatewayClient().AddNettyClient <AmpMessage>(); //注册服务 services.AddSingleton <IHostedService, HangfireHostService>(); }); host.RunConsoleAsync().Wait(); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } UpdateDatabase(app); app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseSwagger(); app.UseHttpsRedirection(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/" + VERSION + "/swagger.json", "WebHook HUB API " + VERSION); c.RoutePrefix = string.Empty; }); app.UseRouting(); app.UseAuthorization(); app.UseMiddleware <Middleware.ApiLoggingMiddleware>(); var dashboardOptions = new DashboardOptions { DashboardTitle = "WebHook Hub - HangFire", Authorization = new[] { new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions { RequireSsl = false, SslRedirect = false, LoginCaseSensitive = true, Users = new [] { new BasicAuthAuthorizationUser { Login = Configuration.GetValue <string>("HangFireConfig:DashboardUserName"), PasswordClear = Configuration.GetValue <string>("HangFireConfig:DashboardPassword") } } }) } }; NavigationMenu.Items.Add(page => new MenuItem("API Documentation", "/index.html")); app.UseHangfireDashboard(Configuration.GetValue <string>("HangFireConfig:DashboardPath"), dashboardOptions); int settingWorkers = Configuration.GetSection("HangFireConfig:WorkerCount").Get <int>(); var options = new BackgroundJobServerOptions { Queues = GetQueuesHangFire(app, Configuration).ToArray() }; if (settingWorkers != 0) { options.WorkerCount = settingWorkers; } app.UseHangfireServer(options, additionalProcesses: new[] { new ProcessMonitor(checkInterval: TimeSpan.FromSeconds(1)) }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); var dogStatsdServer = Configuration.GetValue <string>("Diagnostics:DogStatsDServer"); ConfigureDataDog(dogStatsdServer); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory , HangfireDBContext hangfireContext , MasterDBContext context , ProductionDomainContext productionDomainContext) { Task.Run((() => { //MasterDBInitializerLarge.DbInitialize(context); MasterDBInitializerLarge.DbInitialize(context); } )); HangfireDBInitializer.DbInitialize(hangfireContext); var options = app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >(); app.UseRequestLocalization(options.Value); GlobalConfiguration.Configuration.UseFilter(new AutomaticRetryAttribute { Attempts = 0 }); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseFileServer(); app.UseStaticFiles(); // app.UseSignalR(); app.UseSignalR(router => { router.MapHub <MessageHub>("/MessageHub"); }); var serverOptions = new BackgroundJobServerOptions() { ServerName = "ProcessingUnit", }; app.UseHangfireServer(serverOptions); app.UseHangfireDashboard(); app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API DOC V1"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseRouting(); app.UseCors(); // Conversion of request query jwt token to cookie for switch from dashboard to hangfire ui dashboard app.UseMiddleware <CookieBasedAuthorizationMiddleware>(); app.UseAuthentication(); app.UseAuthorization(); var backgroundJobServerOptions = new BackgroundJobServerOptions { Queues = new[] { "ospSystem", "default" } }; app.UseHangfireServer(backgroundJobServerOptions); app.UseOspPersistence(); app.UseOspApiVersioningAndDocumentation(); var scopeFactory = app.ApplicationServices.GetService <IServiceScopeFactory>(); using (var scope = scopeFactory.CreateScope()) { var userSchemaService = scope.ServiceProvider.GetService <IUserSchemaService>(); userSchemaService.SetupAsync().GetAwaiter().GetResult(); var serviceHookService = scope.ServiceProvider.GetService <IServiceHookService>(); serviceHookService.SyncDataSourceAndCreateJobsAsync().GetAwaiter().GetResult(); } // Because we are behind a load balancer using HTTP it is needed to use XForwardProto to ensure // that requests are send by HTTPS (e. g. Authentication to Identity Server) app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseHttpsRedirection(); var ospOptions = app.ApplicationServices.GetRequiredService <IOptions <OspJobServicesOptions> >(); app.Map("/ui", branchedApp => { // ReSharper disable once ASP0001 branchedApp.UseAuthorization(JobServiceConstants.AuthenticatedUserPolicy); branchedApp.UseHangfireDashboard("/jobs", new DashboardOptions { AppPath = ospOptions.Value.PublicDashboardUrl, Authorization = new[] { new HangfireDashboardAuthorizationFilter() } }); }); app.UseStaticFiles(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } HttpContextCurrent.ServiceProvider = app.ApplicationServices; app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMiddleware <ExceptionHandlingMiddleware>(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #if DEV || DEBUG || UAT app.UseSwagger(); app.UseSwaggerUI(opt => { opt.SwaggerEndpoint("/swagger/Open API Platform/swagger.json", "Open API Platform"); // opt.InjectOnCompleteJavaScript("/Swagger_lang.js"); }); #endif #region Hangfire var jobOptions = new BackgroundJobServerOptions { Queues = new[] { "report" }, WorkerCount = Environment.ProcessorCount * 5, //并发任务数 ServerName = System.Net.Dns.GetHostName(), //服务器名称 }; app.UseHangfireServer(jobOptions); app.UseHangfireDashboard("/hangfire", new DashboardOptions() { Authorization = new[] { new HangfireAthorizationFilter() }, IsReadOnlyFunc = (DashboardContext context) => true, DisplayStorageConnectionString = false, }); app.UseHangfireDashboard(); using (var connection = JobStorage.Current.GetConnection()) { var storageConnection = connection as JobStorageConnection; if (storageConnection != null) { //立即启动 //var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("hangfire start!")); } } #endregion #region Nlog loggerFactory.AddNLog();//添加NLog #if DEV || DEBUG env.ConfigureNLog("nlog.dev.config"); #endif #if UAT env.ConfigureNLog("nlog.uat.config"); #endif #if PROD env.ConfigureNLog("nlog.prod.config"); #endif #endregion }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { //中文乱码问题 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //app.UseCookiePolicy(); //启用认证 app.UseAuthentication(); app.UseHangfireDashboard(); //使用hangfire面板 var options = new BackgroundJobServerOptions { Queues = new[] { "account" }, ServerName = "Account-Service" }; app.UseHangfireServer(options); //启动hangfire服务 //hangfire di GlobalConfiguration.Configuration.UseActivator <HangFireActivator>(new HangFireActivator(serviceProvider)); app.Map("/login", app2 => app2.Run(async context => { var Identity = new ClaimsIdentity(); Identity.AddClaim(new Claim(ClaimTypes.Name, "假永振")); await context.SignInAsync(new ClaimsPrincipal(Identity)); context.Response.Redirect("/"); })); //app.Run(context => //{ // context.Response.ContentType = "text/plain;charset=utf-8"; // return context.Response.WriteAsync( // context.User?.Identity?.IsAuthenticated ?? false ? context.User.Identity.Name : "没有登陆"); //}); //loggerFactory.AddLog4Net(); // << Add this line 转移到Program 下了,添加过滤 //启用中间件服务生成Swagger作为JSON终结点 #if DEBUG app.UseSwagger(); //启用中间件服务对swagger-ui,指定Swagger JSON终结点 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); #endif app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
protected virtual void BuildBackgroundJobServer(TStorage storage, BackgroundJobServerOptions options) { BackgroundJobServer = new BackgroundJobServer(options, storage); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddHealthChecks() //.AddDbContextCheck<Data.ApplicationDbContext>() ; //System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-us"); //System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; services.Configure <HangfireServiceOption>(Configuration.GetSection("HangfireTask")); services.AddHangfire((sp, x) => { try { var _hangfireOption = sp.GetService <Microsoft.Extensions.Options.IOptions <HangfireServiceOption> >()?.Value; var queues = _hangfireOption?.Queues?.ToLower()?.Replace("-", "_")?.Replace(" ", "_")?.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Where(f => !string.IsNullOrWhiteSpace(f)).ToArray();//new[] { "default", "apis", "jobs" }; if (queues == null || queues.Length == 0) { queues = new[] { Hangfire.States.EnqueuedState.DefaultQueue } } ; x .SetDataCompatibilityLevel(CompatibilityLevel.Version_110) //设置数据兼容级别 .UseSimpleAssemblyNameTypeSerializer() //使用简单程序集名称类型序列化程序 .UseRecommendedSerializerSettings() //使用推荐的序列化程序设置 .UseColouredConsoleLogProvider() //使用彩色控制台日志提供程序 .UseConsole() //使用控制台程序(Hangfire.Console) //.UseLog4NetLogProvider()//使用log4net日志提供程序 //.UseNLogLogProvider()//使用NLogLog日志提供程序 //.UseActivator(new OrchardJobActivator(_lifetimeScope)) //.UseFilter(new LogFailureAttribute())//登录失败日志记录 .UseHeartbeatPage(checkInterval: TimeSpan.FromSeconds(1)) .UseManagementPages((config) => { return(config .AddJobs(GetModuleTypes()) //.SetCulture(cultureInfo) //.TranslateJson(< Custom language JSON >) ////or //.TranslateCulture(< Custom Language Object >) ////or //.TranslateStream(< Custom language Stream >); ); }) .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.ServerCount) //服务器数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.RecurringJobCount) //任务数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.RetriesCount) //重试次数 //.UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.EnqueuedCountOrNull)//队列数量 //.UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.FailedCountOrNull)//失败数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.EnqueuedAndQueueCount) //队列数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.ScheduledCount) //计划任务数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.ProcessingCount) //执行中的任务数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.SucceededCount) //成功作业数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.FailedCount) //失败数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.DeletedCount) //删除数量 .UseDashboardMetric(Hangfire.Dashboard.DashboardMetrics.AwaitingCount) //等待任务数量 ; switch (_hangfireOption.StorageType) { case StorageType.SqlServerStorage: { //nameOrConnectionString="server=weberpdb.fd.com;database=Hangfire;uid=sa;pwd=`1q2w3e4r;Application Name=WebErpApp (Hangfire) Data Provider"; UseSqlServerStorage(x, _hangfireOption.nameOrConnectionString, queues); } break; case StorageType.MemoryStorage: x.UseMemoryStorage(); break; //case Settings.StorageType.FirebirdStorage: // break; //case Settings.StorageType.RedisStorage: // //config.UseRedisStorage(); // break; //case Settings.StorageType.FirebaseStorage: // break; //case Settings.StorageType.MongoStorage: // break; //case Settings.StorageType.MySqlStorage: // break; //case Settings.StorageType.PostgreSqlStorage: // break; //case Settings.StorageType.RavenStorage: // break; //case Settings.StorageType.SQLiteStorage: // break; case StorageType.LocalStorage: default: { UseSqlServerStorage(x, $"Data Source=(LocalDb)\\MSSQLLocalDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\Hangfire.mdf", queues); } break; } //.UseSqlServerStorage("server=10.11.1.121;database=Hangfire;uid=sa;pwd=`1q2w3e4r;Application Name=WebErpApp (Hangfire) Data Provider") } catch (Exception ex) { _logger.LogError(ex, "AddHangfire 异常"); throw; } }); services.AddHangfireServer((sp, options) => { var _hangfireOption = sp.GetService <Microsoft.Extensions.Options.IOptions <HangfireServiceOption> >()?.Value; //var _hangfireOption = _hangfireServiceOption?.Value; if (_hangfireOption?.IsUseHangfireServer == true) { var queues = _hangfireOption.Queues?.ToLower() /*?.Replace("-", "_")*/?.Replace(" ", "_")?.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Where(f => !string.IsNullOrWhiteSpace(f)).ToArray();//new[] { "default", "apis", "jobs" }; if (queues == null || queues.Length == 0) { queues = new[] { Hangfire.States.EnqueuedState.DefaultQueue } } ; //启用本地服务 options = new BackgroundJobServerOptions {//:{System.Web.Hosting.HostingEnvironment.SiteName }:{System.Web.Hosting.HostingEnvironment.ApplicationID} ServerName = $"{(string.IsNullOrWhiteSpace(_hangfireOption?.ServiceName) ? "" : ("[" + _hangfireOption?.ServiceName + "]"))}{Environment.MachineName}:{System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}:{AppDomain.CurrentDomain.FriendlyName}:{System.Diagnostics.Process.GetCurrentProcess().Id}:{AppDomain.CurrentDomain.Id}", //[]mccj-pc:webuiapp:32732:1 ShutdownTimeout = TimeSpan.FromMinutes(30), //关闭超时时间 WorkerCount = Math.Max(Environment.ProcessorCount, _hangfireOption.WorkerCount == 0 ? 20 : _hangfireOption.WorkerCount), //最大job并发处理数量 Queues = queues }; return(true); } return(false); }); }
public void Start() { var options = new BackgroundJobServerOptions(); _server = new BackgroundJobServer(options); }
public static IApplicationBuilder UseHangfireServer( [NotNull] this IApplicationBuilder builder, [NotNull] BackgroundJobServerOptions options) { return(builder.UseHangfireServer(options, JobStorage.Current)); }
public override void ConfigureHangfireServer(TenantBuilderContext context, BackgroundJobServerOptions options) { }
public void Configure(IApplicationBuilder app, IOptions <SenparcSetting> senparcSetting) { // 初始化ABP框架 app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); if (_env.IsDevelopment()) { app.UseDeveloperExceptionPage(); // app.UseBrowserLink(); } else { app.UseStatusCodePagesWithRedirects("~/Error?statusCode={0}"); app.UseExceptionHandler("/Error"); } //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hosting Environment: " + _env.EnvironmentName); //}); // Use Wechat SenparcWXConfigurer.UseWechat(_env, senparcSetting.Value); // 启用静态文件 app.UseStaticFiles(); app.UseRouting(); // 启用CORS app.UseCors(_defaultCorsPolicyName); // 启用校验 app.UseAuthentication(); app.UseJwtTokenMiddleware(); app.UseAuthorization(); app.UseAbpRequestLocalization(); #region 是否启用Hangfire //是否启用Hangfire if (WebConsts.HangfireDashboardEnabled) { //配置服务最大重试次数值 GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 5 }); //设置Hangfire服务可选参数 var jobOptions = new BackgroundJobServerOptions { //wait all jobs performed when BackgroundJobServer shutdown. ShutdownTimeout = TimeSpan.FromMinutes(30), Queues = new[] { "default", "jobs" }, //队列名称,只能为小写 WorkerCount = 3, //Environment.ProcessorCount * 5, //并发任务数 Math.Max(Environment.ProcessorCount, 20) ServerName = "yoyosoft.hangfire", }; //启用Hangfire仪表盘和服务器(支持使用Hangfire而不是默认的后台作业管理器) app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new AbpHangfireAuthorizationFilter(YoyoSoftPermissionNames.Pages_Administration_HangfireDashboard) } }); app.UseHangfireServer(jobOptions); // app.UseHangfireServer(); } #endregion 是否启用Hangfire app.UseEndpoints(endpoints => { endpoints.MapHub <AbpCommonHub>("/signalr"); endpoints.MapHub <ChatHub>("/signalr-chat"); endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); if (bool.Parse(_appConfiguration["HealthChecks:HealthChecksEnabled"])) { endpoints.MapHealthChecks("/healthz", new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); endpoints.MapHealthChecksUI(); } }); if (bool.Parse(_appConfiguration["HealthChecks:HealthChecksEnabled"])) { if (bool.Parse(_appConfiguration["HealthChecks:HealthChecksUI:HealthChecksUIEnabled"])) { app.UseHealthChecksUI(); } } if (WebConsts.SwaggerUiEnabled) { // 使中间件能够作为JSON端点提供生成的Swagger app.UseSwagger(); // 使中间件能够提供swagger-ui(HTML、JS、CSS等) app.UseSwaggerUI(options => { // SwaggerEndPoint options.SwaggerEndpoint(_appConfiguration["App:SwaggerEndPoint"], "YoyoCmsTemplate API V1"); options.EnableDeepLinking(); options.DocExpansion(DocExpansion.None); options.IndexStream = () => Assembly.GetExecutingAssembly() .GetManifestResourceStream("LTMCompanyName.YoyoCmsTemplate.Web.Host.wwwroot.swagger.monitor.index.html"); }); // URL: /swagger } // Enable middleware to serve generated Swagger as a JSON endpoint }
/// <summary> /// Tells bootstrapper to start a job server with the given /// options on application start and stop it automatically /// on application shutdown request. Global job storage is being used. /// </summary> /// <param name="configuration">Configuration</param> /// <param name="options">Job server options</param> public static void UseServer( this IBootstrapperConfiguration configuration, BackgroundJobServerOptions options) { configuration.UseServer(() => new BackgroundJobServer(options)); }
public static void Main() { GlobalConfiguration.Configuration .UseColouredConsoleLogProvider() .UseSqlServerStorage(@"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;") .UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical"); RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely); RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *"); RecurringJob.AddOrUpdate("Hawaiian", () => Console.WriteLine("Hawaiian"), "15 08 * * *", TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time")); RecurringJob.AddOrUpdate("UTC", () => Console.WriteLine("UTC"), "15 18 * * *"); RecurringJob.AddOrUpdate("Russian", () => Console.WriteLine("Russian"), "15 21 * * *", TimeZoneInfo.Local); var options = new BackgroundJobServerOptions { Queues = new[] { "critical", "default" } }; using (new BackgroundJobServer(options)) { var count = 1; while (true) { var command = Console.ReadLine(); if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase)) { break; } 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); } } if (command.StartsWith("generic", StringComparison.OrdinalIgnoreCase)) { BackgroundJob.Enqueue <GenericServices <string> >(x => x.Method("hello", 1)); } if (command.StartsWith("continuations", StringComparison.OrdinalIgnoreCase)) { WriteString("Hello, Hangfire continuations!"); } } } Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.GetServiceProvider(); app.UseSession(); //静态文件 app.UseStaticFiles(); //认证 app.UseAuthentication(); //路由 app.UseRouting(); //授权 app.UseAuthorization(); //使用HangFire自动化任务调度 var hangJobOption = new BackgroundJobServerOptions() { //服务器名字 ServerName = Environment.MachineName, //最大并行数 WorkerCount = 3, //执行任务队列 Queues = new string[] { "default", "api" } }; app.UseHangfireServer(hangJobOption); //设置HangFire控制面板权限验证 var hangJobAuth = new BasicAuthAuthorizationFilter( new BasicAuthAuthorizationFilterOptions { //加密重定向 SslRedirect = false, //需要Ssl Https RequireSsl = false, //忽略大小写 LoginCaseSensitive = false, Users = new[] { //配置账号密码 new BasicAuthAuthorizationUser { Login = "******", Password = Encoding.UTF8.GetBytes("CommonSystem"), PasswordClear = "CommonSystem" } } } ); //改变原本访问后台任务路径 app.UseHangfireDashboard("/TaskManager", new DashboardOptions { Authorization = new[] { hangJobAuth } }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute(name: "Default", pattern: "{Controller=Home}/{Action=Index}/{id?}"); endpoints.MapRazorPages(); }); #warning 待添加 //记录访问 记录Middleware app.UseMiddleware <VisitMiddleWare>(); //初始化数据库及初始数据 Task.Run(async() => { using (var scope = app.ApplicationServices.CreateScope()) { var meuns = MeunHelper.GetMeunes(); var dbservice = scope.ServiceProvider.GetService <IDatabaseInitService>(); await dbservice.InitAsync(meuns); } }); //添加一个每天自动在凌晨的时候执行的统计任务 待完善 //RecurringJob.AddOrUpdate<ISiteViewService>(x => x.AddOrUpdate(), Cron.Daily()); //RecurringJob.AddOrUpdate<Test>(n=>n.TestConsoleStr(DateTime.Now.ToString()), Cron.Minutely()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); app.UseHttpsRedirection(); } app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "DWAPI Central MNCH API"); //c.SupportedSubmitMethods(new Swashbuckle.AspNetCore.SwaggerUI.SubmitMethod[] { }); }); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); EnsureMigrationOfContext <MnchContext>(serviceProvider); Mapper.Initialize(cfg => { cfg.AddDataReaderMapping(); } ); #region HangFire try { app.UseHangfireDashboard(); var options = new BackgroundJobServerOptions { ServerName = "DWAPIMNCHMAIN", WorkerCount = 1 }; app.UseHangfireServer(options); GlobalJobFilters.Filters.Add(new ProlongExpirationTimeAttribute()); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute() { Attempts = 3 }); } catch (Exception e) { Log.Fatal(e, "Hangfire is down !"); } #endregion try { DapperPlusManager.AddLicense("1755;700-ThePalladiumGroup", "218460a6-02d0-c26b-9add-e6b8d13ccbf4"); if (!DapperPlusManager.ValidateLicense(out var licenseErrorMessage)) { throw new Exception(licenseErrorMessage); } } catch (Exception e) { Log.Debug($"{e}"); throw; } Log.Debug(@"initializing Database [Complete]"); Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug(@" ________ .__ _________ __ .__ \______ \__ _ _______ ______ |__| \_ ___ \ ____ _____/ |_____________ | | | | \ \/ \/ /\__ \ \____ \| | / \ \/_/ __ \ / \ __\_ __ \__ \ | | | ` \ / / __ \| |_> > | \ \___\ ___/| | \ | | | \// __ \| |__ /_______ /\/\_/ (____ / __/|__| /\ \______ /\___ >___| /__| |__| (____ /____/ \/ \/|__| \/ \/ \/ \/ \/ "); Log.Debug( @"---------------------------------------------------------------------------------------------------"); Log.Debug("Dwapi Central MNCH started !"); }
public static void Main() { GlobalConfiguration.Configuration .UseColouredConsoleLogProvider() .UseSqlServerStorage(@"server=.;database=Hangfire;uid=hf;pwd=hf123;"); //.UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical"); //RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely); //RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *"); //RecurringJob.AddOrUpdate("Hawaiian", () => Console.WriteLine("Hawaiian"), "15 08 * * *", TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time")); //RecurringJob.AddOrUpdate("UTC", () => Console.WriteLine("UTC"), "15 18 * * *"); //RecurringJob.AddOrUpdate("Russian", () => Console.WriteLine("Russian"), "15 21 * * *", TimeZoneInfo.Local); var options = new BackgroundJobServerOptions { Queues = new[] { "critical", "default" }, //队列名称,只能小写字母 //WorkerCount = Environment.ProcessorCount * 5, //并发任务数 //ServerName = "hangfire1", //服务器名称 }; /* * Queues要处理的队列列表 * 对于多个服务器同时连接到数据库,Hangfire会认为他们是分布式中的一份子。 * 现实中不同服务器往往存在着差异,这个时候就需要合理配置服务器(应用)的处理队列。 * 例如: * 对于服务器性能差异的处理,有100个A任务和50个B任务需要处理,假设A服务器的性能是B服务器的两倍,如果不配置队列,那么会平分任务给两个服务器。 * 如果我们只让B服务器处理B任务,而A服务器同时处理两种任务,这样B就能减少一些压力。 * * WorkerCount并发任务数,超出并发数将等待之前的任务完成。 * 默认的并发任务数是线程(cpu)的5倍,如果IO密集型任务多而CPU密集型的任务少,可以考虑调高并发任务数。 * */ /* * 任务类型 * Fire-and-forget 直接将任务加入到待执行任务队列。 * Delayed 在当前时间后的某个时间将任务加入到待执行任务队列。 * Recurring 周期性任务,每一个周期就将任务加入到待执行任务队列。 * Continuations 继续执行任务。 */ using (new BackgroundJobServer(options)) { var count = 1; while (true) { var command = Console.ReadLine(); var workCount = 1; var cmds = command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); command = cmds[0]; if (cmds.Length > 1) { workCount = cmds[1].ToInt(1); } if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase)) { break; } _add(command, workCount); _async(command, workCount); _static(command, workCount); _error(command, workCount); _args(command, workCount); _custom(command, workCount); _fullargs(command, workCount); _in(command, ref count, workCount); _cancelable(command, workCount); _delete(command, workCount); _fast(command, workCount); _generic(command); _continuations(command); } } Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); }
public static (BackgroundJobServer server, IRecurringJobManager recurringJobManager, IBackgroundJobClient backgroundJobClient) StartHangfireServer(BackgroundJobServerOptions options, string connectionString) { JobStorage storage; if (string.IsNullOrWhiteSpace(connectionString)) { storage = new MemoryStorage(); } else if (ConnectionStringHelper.IsSQLite(connectionString)) { storage = new SQLiteStorage(connectionString); } else { storage = new SqlServerStorage(connectionString); } var filterProvider = JobFilterProviders.Providers; var activator = JobActivator.Current; var backgroundJobFactory = new BackgroundJobFactory(filterProvider); var performer = new BackgroundJobPerformer(filterProvider, activator); var backgroundJobStateChanger = new BackgroundJobStateChanger(filterProvider); IEnumerable <IBackgroundProcess> additionalProcesses = null; var server = new BackgroundJobServer(options, storage, additionalProcesses, options.FilterProvider ?? filterProvider, options.Activator ?? activator, backgroundJobFactory, performer, backgroundJobStateChanger); var recurringJobManager = new RecurringJobManager(storage, backgroundJobFactory); var backgroundJobClient = new BackgroundJobClient(storage, backgroundJobFactory, backgroundJobStateChanger); return(server, recurringJobManager, backgroundJobClient); }