static void InitializeHangfireServer() { if (CacheData.FatalError) { return; } var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = Convert.ToBoolean(CacheData.Configuration["HFPrepareSchema"]), QueuePollInterval = TimeSpan.FromSeconds( Convert.ToInt32(CacheData.Configuration["HFPollingInterval"])) }; GlobalConfiguration.Configuration.UseSqlServerStorage(CacheData.Configuration["HFDatabase"], options); GlobalConfiguration.Configuration.UseLogProvider(new HFLogProvider()); backgroundJobServer = new BackgroundJobServer(); Data.Utils.Logging.AddLog(new Models.SystemLog() { LoggerName = CacheData.LoggerName, Date = DateTime.Now, Function = "InitializeHangfireServer", Level = Models.SystemLog.Levels.Info, Message = "Hangifre server started", UserId = -1 }); ClearHangfireJobs(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { 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.AddDbContext <MydbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MydbContext"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddHangfire(config => { var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false, QueuePollInterval = TimeSpan.FromMinutes(5) }; config.UseSqlServerStorage("MydbContext", options); }); services.AddScoped <IMyJob, MyJob>(); }
private static void ConfigureHangfireServer() { Console.WriteLine("== SERVER START =="); LogProvider.SetCurrentLogProvider(new ColouredConsoleLogProvider()); var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true }; GlobalConfiguration.Configuration .UseSqlServerStorage("Scheduler", options) .UseColouredConsoleLogProvider(); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 }); using (var server = new BackgroundJobServer()) { Console.WriteLine("== SERVER STARTED =="); Console.ReadKey(); } }
public override void Configuration(IAppBuilder app) { //ensure the default options are configured base.Configuration(app); // Configure hangfire var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true }; const string umbracoConnectionName = Umbraco.Core.Constants.System.UmbracoConnectionName; var connectionString = System.Configuration .ConfigurationManager .ConnectionStrings[umbracoConnectionName] .ConnectionString; GlobalConfiguration.Configuration .UseSqlServerStorage(connectionString, options) .UseConsole(); // Give hangfire a URL and start the server var dashboardOptions = new DashboardOptions { Authorization = new[] { new UmbracoAuthorizationFilter() } }; app.UseHangfireDashboard("/hangfire", dashboardOptions); app.UseHangfireServer(); // Schedule jobs var scheduler = new ScheduleHangfireJobs(); scheduler.ScheduleStaleContent(); }
public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsNegative() { var options = new SqlServerStorageOptions(); Assert.Throws <ArgumentException>( () => options.QueuePollInterval = TimeSpan.FromSeconds(-1)); }
public override void Configuration(IAppBuilder app) { //ensure the default options are configured base.Configuration(app); var clientId = WebConfigurationManager.AppSettings["GoogleOAuthClientID"]; var secret = WebConfigurationManager.AppSettings["GoogleOAuthSecret"]; app.ConfigureBackOfficeGoogleAuth(clientId, secret); if (string.Equals(ConfigurationManager.AppSettings["HangFireEnabled"], "true", StringComparison.InvariantCultureIgnoreCase) == false) { return; } // Configure hangfire var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true }; var connectionString = Umbraco.Core.ApplicationContext.Current.DatabaseContext.ConnectionString; GlobalConfiguration.Configuration.UseSqlServerStorage(connectionString, options); var dashboardOptions = new DashboardOptions { Authorization = new[] { new UmbracoAuthorizationFilter() } }; app.UseHangfireDashboard("/hangfire", dashboardOptions); app.UseHangfireServer(); // Schedule jobs var scheduler = new ScheduleHangfireJobs(); scheduler.MarkAsSolvedReminder(); }
private static void ConfigurarHangFire(IAppBuilder app) { // Configurar HangFire var pollTime = System.Configuration.ConfigurationManager.AppSettings["PollTimeHangFire"]; var time = System.Configuration.ConfigurationManager.AppSettings["TimeHangFire"]; int intPollTime; if (int.TryParse(pollTime, out intPollTime)) { var options = new SqlServerStorageOptions { QueuePollInterval = System.TimeSpan.FromHours(intPollTime) }; SG_SST.Controllers.Organizacion.CompetenciaController competencia = new Controllers.Organizacion.CompetenciaController(); GlobalConfiguration.Configuration.UseSqlServerStorage("SG_SSTContext", options); //BackgroundJob.Enqueue(() => System.Console.WriteLine("Fire-and-forgetIII!")) //cola // BackgroundJob.Schedule(() => competencia.LeerExcel(), System.TimeSpan.FromSeconds(30)); //calendarizar //every 30 minutes // RecurringJob.AddOrUpdate(() => oc.SearchFinalDate(), "*/3 * * * *"); //RecurringJob.AddOrUpdate(() => oc.SearchFinalDate(), "* * * * *"); //at 15 minutes every hour every day //RecurringJob.AddOrUpdate(() => competencia.LeerExcel(), "15 * * * *"); //at 00:00 every day RecurringJob.AddOrUpdate(() => competencia.LeerExcel(), time); app.UseHangfireDashboard(); app.UseHangfireServer(); } else { throw new System.ArgumentException("La clave PollTimeHangFire no tiene un valor entero valido."); } }
public SqlStorageFacts() { _options = new SqlServerStorageOptions() { PrepareSchemaIfNecessary = false }; }
public void Configuration(IAppBuilder app) { JsonConvert.DefaultSettings = (() => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new StringEnumConverter()); return(settings); }); ConfigureAuth(app); var options = new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(15) // Default value }; var daKey = ConfigurationManager.AppSettings["StripeApiKey"]; StripeConfiguration.SetApiKey(daKey); Hangfire.GlobalConfiguration.Configuration .UseSqlServerStorage(ConfigurationManager.ConnectionStrings["PoolReservation"].ConnectionString, options); app.UseHangfireServer(); app.UseHangfireDashboard("/hangfire"); //app.UseHangfireDashboard("/hangfire", new DashboardOptions //{ // Authorization = new[] { new HangfireIdentityAuthentication() } //}); }
public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsEqualToZero() { var options = new SqlServerStorageOptions(); Assert.Throws <ArgumentException>( () => options.QueuePollInterval = TimeSpan.Zero); }
private static void Start(bool enableSchemaMigration) { var schemaName = "adminapp_hangfire"; var connectionString = Startup.ConfigurationConnectionStrings.Admin; var isPostgreSql = "PostgreSQL".Equals( Startup.ConfigurationAppSettings.DatabaseEngine, StringComparison.InvariantCultureIgnoreCase); if (isPostgreSql) { var options = new PostgreSqlStorageOptions { SchemaName = schemaName }; GlobalConfiguration.Configuration.UsePostgreSqlStorage(connectionString, options); } else { var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = enableSchemaMigration, SchemaName = schemaName }; GlobalConfiguration.Configuration.UseSqlServerStorage(connectionString, options); } }
public void Configuration(IAppBuilder app) { // Map Dashboard to the `http://<your-app>/hangfire` URL. //ConnectionService.SetConnectionString(); var connectionFactory = new HelperConnectionFactory(ConnectionHelper.Helper()); var configurationRepo = new ConfigurationRepository(connectionFactory); var queuePollInterval = Math.Max( configurationRepo.ReadValue <int>(ConfigurationKeys.QueuePollInterval) ?? Defaults.Queuing.DefaultQueuePollInterval, Defaults.Queuing.MinQueuePollInterval); var sqlHangfireOptions = new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(queuePollInterval) }; using (var conn = connectionFactory.GetEddsPerformanceConnection()) { GlobalConfiguration.Configuration.UseSqlServerStorage(conn.ConnectionString, sqlHangfireOptions); } var options = new DashboardOptions { AppPath = VirtualPathUtility.ToAbsolute("~"), Authorization = new[] { new AuthenticateUserAttribute() } }; app.UseHangfireDashboard("/hangfire", options); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.Configure <AppSettings>(Configuration); if (AppSettings.CheckDependency.Enabled) { var hosts = AppSettings.CheckDependency.Host.Split(','); foreach (var host in hosts) { NetworkPortCheck.Wait(host, 5); } } services.AddHangfire(x => { var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true, }; x.UseSqlServerStorage(AppSettings.ConnectionStrings.ClassifiedAds, options); }); services.AddDateTimeProvider(); services.AddNotificationModule(AppSettings.MessageBroker, AppSettings.Notification, AppSettings.ConnectionStrings.ClassifiedAds) .AddApplicationServices(); services.AddMessageBusReceiver <FileUploadedEvent>(AppSettings.MessageBroker); services.AddMessageBusReceiver <FileDeletedEvent>(AppSettings.MessageBroker); services.AddMessageBusReceiver <EmailMessageCreatedEvent>(AppSettings.MessageBroker); services.AddMessageBusReceiver <SmsMessageCreatedEvent>(AppSettings.MessageBroker); services.AddHostedService <ResendEmailHostedService>(); services.AddHostedService <ResendSmsHostedService>(); }
public void Configuration(IAppBuilder app) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DbCS"].ConnectionString; var options = new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(30)// Default value }; Log.Logger = new LoggerConfiguration() .WriteTo.Console(Serilog.Events.LogEventLevel.Debug) .WriteTo.Console(Serilog.Events.LogEventLevel.Error) .WriteTo.Console(Serilog.Events.LogEventLevel.Warning) .WriteTo.Console(Serilog.Events.LogEventLevel.Information) .WriteTo.File(@"C:\tempLog\JobAgentLog.txt") .CreateLogger(); GlobalConfiguration.Configuration .UseSqlServerStorage(connectionString, options); app.UseHangfireDashboard("/jobs"); ServiceScheduler.ScheduleJobs(); }
/// <summary> /// Configures Services collection to use hangfire worker provider. /// </summary> /// <param name="services">Application's services collection instance</param> /// <param name="variant">While this will likely be your environment name (Development, Production, etc...), it could be any custom 'appsettings.{variant}.json' as well.</param> public static IServiceCollection AddBackgroundWorkers(this IServiceCollection services, IConfigurationRoot config) { var workerConfig = config.GetSection("WorkersHangfire").Get <HangfireWorkerConfiguration>(); var connectionString = ConfigurationUtils.GetConnectionString(); var sqlOptions = new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(workerConfig.SqlServerOptions.CommandBatchMaxTimeout), DisableGlobalLocks = workerConfig.SqlServerOptions.DisableGlobalLocks, QueuePollInterval = TimeSpan.FromMinutes(workerConfig.SqlServerOptions.QueuePollInterval), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(workerConfig.SqlServerOptions.SlidingInvisibilityTimeout), UsePageLocksOnDequeue = workerConfig.SqlServerOptions.UsePageLocksOnDequeue, UseRecommendedIsolationLevel = workerConfig.SqlServerOptions.UseRecommendedIsolationLevel }; services.AddBackgroundWorkerDependencies(); Console.WriteLine($"Connecting to Hangfire SqlServer Storage => {connectionString}"); services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(connectionString, sqlOptions)); // Add the processing server as IHostedService services.AddHangfireServer(); return(services); }
public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration Configuration, IGlobalConfiguration globalConfiguration) { var serverProvider = services.BuildServiceProvider(); var hangfireSettings = serverProvider.GetService <IOptions <HangfireSettings> >().Value; var httpJobOptions = serverProvider.GetService <IOptions <HangfireHttpJobOptions> >().Value; var sqlConnectStr = Configuration.GetSection(HangfireConnectStringKey).Get <string>(); var mssqlOption = new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true }; globalConfiguration.UseSqlServerStorage(sqlConnectStr, mssqlOption) .UseConsole(new ConsoleOptions { BackgroundColor = "#000079" }) .UseTagsWithSql(new TagsOptions() { TagsListStyle = TagsListStyle.Dropdown }) .UseHangfireHttpJob(httpJobOptions) .UseHeartbeatPage(); }
public void OneTimeSetUp() { _msSqlDatabase = MsSqlHelpz.CreateDatabase("hangfire"); var sqlServerStorageOptions = new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1), }; _log = new HangfireJobLog(); var jobFilterCollection = new JobFilterCollection { _log }; var backgroundJobServerOptions = new BackgroundJobServerOptions { SchedulePollingInterval = TimeSpan.FromSeconds(1), FilterProvider = jobFilterCollection }; GlobalConfiguration.Configuration .UseSqlServerStorage(_msSqlDatabase.ConnectionString.Value, sqlServerStorageOptions) .UseActivator(new DelegatingActivator(() => _eventFlowResolverActivator)); _backgroundJobServer = new BackgroundJobServer(backgroundJobServerOptions); }
public void ConfigureHangfire(IAppBuilder app) { //if (System.Configuration.ConfigurationManager.ConnectionStrings["SPPContext"] != null) //{ var optionsDB = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false }; //data source=JUSTIN\SQL2014;initial catalog=PDMS_Test;persist security info=True;user id=sa;password=123;MultipleActiveResultSets=True; //data source=CNCTUG0PDMSTST1;initial catalog=PDMS_Test;persist security info=True;user id=justin;password=P@SSw0rd@1234;MultipleActiveResultSets=True;App=EntityFramework" GlobalConfiguration.Configuration.UseSqlServerStorage(@"data source=CNCTUG0PDMSTST1;initial catalog=PDMS_Dev;persist security info=True;user id=justin;password=P@SSw0rd@1234;MultipleActiveResultSets=True;App=EntityFramework""); GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 }); var options = new BackgroundJobServerOptions { WorkerCount = Environment.ProcessorCount * 5, Queues = new[] { Environment.MachineName.ToLower() } }; app.UseHangfireDashboard(); app.UseHangfireServer(options); //} }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { 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_2); var optionsHangFire = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true }; services.AddHangfireWithContext((y, x) => x .UseSqlServerStorage("Data Source=localhost;Initial Catalog=Hangfire;Trusted_Connection=True;", optionsHangFire) .UseActivator(new AspNetCoreJobActivatorWithContext(y.GetService <IServiceScopeFactory>())) ); services.AddHangfireServer(); services.AddScoped <IAgendador, Agendador>(); services.AddScoped <IFazedor, Fazedor>(); services.AddScoped <IHangfireContextProvider, HangfireContextProvider>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <IISOptions>(options => { options.AutomaticAuthentication = false; }); var dbConnection = Configuration.GetConnectionString("Database"); services.AddControllers(); services.AddHangfire(x => { var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true, CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(30), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true, }; x.UseSqlServerStorage(dbConnection, options); }); services.AddScoped <IJobProcessor, JobProcessor>(provider => new JobProcessor(Configuration.GetValue <string>("Url"), provider.GetService <ILoggerFactory>())); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi Api", Version = "v1" }); }); }
public void Set_QueuePollInterval_SetsTheValue() { var options = new SqlServerStorageOptions(); options.QueuePollInterval = TimeSpan.FromSeconds(1); Assert.Equal(TimeSpan.FromSeconds(1), options.QueuePollInterval); }
/// <summary> /// Setup the basics for <see cref="Hangfire"/>, database connectivity and security on urls /// </summary> private static void ConfigureHangfire(IAppBuilder app) { Thread.Sleep(1000); var sqlServerStorageOptions = new SqlServerStorageOptions { // We have scripted out the Hangfire tables, so we tell Hangfire not to insert them. // This might be an issue when Hangfire does a change to its schema, but this should work for now. PrepareSchemaIfNecessary = false }; GlobalConfiguration.Configuration.UseSqlServerStorage(FirmaWebConfiguration.DatabaseConnectionString, sqlServerStorageOptions); app.UseHangfireServer(new BackgroundJobServerOptions { WorkerCount = 1, Queues = new[] { "critical", "default" }, ServerName = "ProjectFirma:1337" }); // 11/03/2015 MF - limit the number of worker threads, we really don't need that many - in fact we try to have each job run serially for the time being because we're not sure how concurrent the different jobs could really be. // Hangfire defaults to 10 retries for failed jobs; this disables that behavior by doing no automatic retries. // http://hangfire.readthedocs.org/en/latest/background-processing/dealing-with-exceptions.html // Note that specific jobs may override this; look for uses of the AutomaticRetry symbol on specific job start functions. GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 }); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> public void ConfigureServices(IServiceCollection services) { var connectionString = _configuration.GetSection("ConnectionStrings")["DefaultConnection"]; services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddDbContext <ApiDbContext>(options => options.UseSqlServer(connectionString)); services.AddSingleton <IMemoryCache, MemoryCache>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "EFCoreApi", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddHangfire(conf => { var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false, QueuePollInterval = TimeSpan.FromMinutes(5) }; conf.UseSqlServerStorage(connectionString, options); }); services.AddScoped <IUpdateDataJob, UpdateDataJob>(); services.AddAuthorization(); services.AddHealthChecks(); services.AddControllers(); }
private void ConfigureHangfire(IApplicationBuilder app) { const string queueName = @".\private$\hangfire_health"; if (!MessageQueue.Exists(queueName)) { var queue = MessageQueue.Create(queueName, true); queue.SetPermissions("Administrators", MessageQueueAccessRights.FullControl); } var options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true }; GlobalConfiguration.Configuration .UseSqlServerStorage("Server=.\\sqlexpress;Database=HangfireHealth;Trusted_Connection=True;MultipleActiveResultSets=true", options) .UseMsmqQueues(queueName) .UseDIActivator(app.ApplicationServices) .UseDashboardMetric(DashboardMetrics.ScheduledCount) .UseDashboardMetric(DashboardMetrics.RetriesCount) .UseDashboardMetric(DashboardMetrics.ProcessingCount) .UseDashboardMetric(DashboardMetrics.SucceededCount) .UseDashboardMetric(DashboardMetrics.FailedCount) .UseDashboardMetric(DashboardMetrics.AwaitingCount); app.UseHangfireServer(); app.UseHangfireDashboard("/hangfire", new DashboardOptions { AuthorizationFilters = new[] { new HangfireAuthorizationFilter() } }); }
public void ShouldPassDefaultStorageOptionsToHangfire() { var system = new SystemUnderTest(); system.ConfigurationStorage.Has(new StoredConfiguration { Active = true, ConnectionString = @"Data Source=." }); system.WorkerServerStarter.Start(); var options = new SqlServerStorageOptions(); var storage = system.Hangfire.StartedServers.Single().storage; Assert.AreEqual(options.QueuePollInterval, storage.SqlServerOptions.QueuePollInterval); Assert.AreEqual(options.SlidingInvisibilityTimeout, storage.SqlServerOptions.SlidingInvisibilityTimeout); Assert.AreEqual(options.JobExpirationCheckInterval, storage.SqlServerOptions.JobExpirationCheckInterval); Assert.AreEqual(options.CountersAggregateInterval, storage.SqlServerOptions.CountersAggregateInterval); Assert.AreEqual(options.PrepareSchemaIfNecessary, storage.SqlServerOptions.PrepareSchemaIfNecessary); Assert.AreEqual(options.DashboardJobListLimit, storage.SqlServerOptions.DashboardJobListLimit); Assert.AreEqual(options.TransactionTimeout, storage.SqlServerOptions.TransactionTimeout); Assert.AreEqual(options.DisableGlobalLocks, storage.SqlServerOptions.DisableGlobalLocks); Assert.AreEqual(options.UsePageLocksOnDequeue, storage.SqlServerOptions.UsePageLocksOnDequeue); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); var connectionString = Configuration["ConnectionStrings:ToDoListConn"]; services.AddDbContext <ToDoListDbContext>(option => option.UseSqlServer(connectionString)); var hangfireConnectionString = Configuration["ConnectionStrings:HangfireConn"]; services.AddHangfire(config => { var option = new SqlServerStorageOptions { PrepareSchemaIfNecessary = true, QueuePollInterval = TimeSpan.FromMinutes(5), CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true }; config.UseSqlServerStorage(hangfireConnectionString, option) .WithJobExpirationTimeout(TimeSpan.FromHours(6)); }); services.AddSwaggerDocument(); services.AddScoped <IMailService, MailManager>(); services.Configure <SmtpConfigDto>(Configuration.GetSection("SmtpConfig")); }
public void ConfigureServices(IServiceCollection services) { services.CustomConfigureServices(Configuration); //hangfire configure services.AddHangfire(config => { var options = new SqlServerStorageOptions { // Veritabanýnda tablolarýn yaratýlýp yaratýlmayacaðý bilgisi // Manuel migration iþlemleri için false yapýlabilir // Default deðeri true PrepareSchemaIfNecessary = true, // Hangfire'ýn ne kadar süre aralýkta kontrol edeceði bilgisi // Default deðeri 15 saniye QueuePollInterval = TimeSpan.FromMinutes(2), CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), //Komut Toplu Maksimum Zaman Aþýmý SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), //Kayan Görünmezlik Zaman Aþýmý UseRecommendedIsolationLevel = true, //Önerilen Ýzolasyon Seviyesini Kullanýn UsePageLocksOnDequeue = true, //Sýradan Çýkarýrken Sayfa Kilitlerini Kullan DisableGlobalLocks = true //Global Kilitleri Devre Dýþý Býrak }; config.UseSqlServerStorage(Configuration.GetConnectionString("Default"), options).WithJobExpirationTimeout(TimeSpan.FromHours(6)); }); services.AddHangfireServer(); }
public SqlTagsTransaction(SqlServerStorageOptions options, IWriteOnlyTransaction transaction) { if (transaction.GetType().Name != "SqlServerWriteOnlyTransaction") { throw new ArgumentException("The transaction is not an SQL transaction", nameof(transaction)); } _options = options; _transaction = transaction; // Dirty, but lazy...we would like to execute these commands in the same transaction, so we're resorting to reflection for now // Other transaction type, clear cached methods if (_type != transaction.GetType()) { _acquireSetLock = null; _queueCommand = null; _addCommand = null; _type = transaction.GetType(); } if (_acquireSetLock == null) { _acquireSetLock = transaction.GetType().GetTypeInfo().GetMethod(nameof(AcquireSetLock), BindingFlags.NonPublic | BindingFlags.Instance); } if (_acquireSetLock == null) { throw new ArgumentException("The function AcquireSetLock cannot be found."); } if (_queueCommand == null) { _queueCommand = transaction.GetType().GetTypeInfo().GetMethod(nameof(QueueCommand), BindingFlags.NonPublic | BindingFlags.Instance); } if (_queueCommand == null && _addCommand == null) { _addCommand = transaction.GetType().GetTypeInfo().GetMethod(nameof(AddCommand), BindingFlags.NonPublic | BindingFlags.Instance); _addCommand = _addCommand?.MakeGenericMethod(typeof(string)); } if (_sqlCommandBatchParameter == null) { _sqlCommandBatchParameter = Type.GetType("Hangfire.SqlServer.SqlCommandBatchParameter, Hangfire.SqlServer"); _sqlCommandBatchParameterCtor = _sqlCommandBatchParameter.GetConstructor(new Type[] { typeof(string), typeof(DbType), typeof(int?) }); _sqlCommandBatchParameterValue = _sqlCommandBatchParameter.GetProperty("Value"); } if (_queueCommand == null && _addCommand == null) { throw new ArgumentException("The functions QueueCommand and AddCommand cannot be found."); } }
public void Ctor_SetsTheDefaultOptions() { var options = new SqlServerStorageOptions(); Assert.True(options.QueuePollInterval > TimeSpan.Zero); Assert.True(options.InvisibilityTimeout > TimeSpan.Zero); Assert.True(options.PrepareSchemaIfNecessary); }
public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration configuration, IGlobalConfiguration globalConfiguration) { var serverProvider = services.BuildServiceProvider(); var langStr = configuration.GetSection(HangfireLangKey).Get <string>(); var envLangStr = GetEnvConfig <string>("Lang"); if (!string.IsNullOrEmpty(envLangStr)) { langStr = envLangStr; } if (!string.IsNullOrEmpty(langStr)) { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(langStr); } var hangfireSettings = serverProvider.GetService <IOptions <HangfireSettings> >().Value; ConfigFromEnv(hangfireSettings); var httpJobOptions = serverProvider.GetService <IOptions <HangfireHttpJobOptions> >().Value; ConfigFromEnv(httpJobOptions); httpJobOptions.GlobalSettingJsonFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory !, "hangfire", "hangfire_global.json"); var sqlConnectStr = configuration.GetSection(HangfireConnectStringKey).Get <string>(); var envSqlConnectStr = GetEnvConfig <string>("HangfireSqlserverConnectionString"); if (!string.IsNullOrEmpty(envSqlConnectStr)) { sqlConnectStr = envSqlConnectStr; } var mssqlOption = new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true }; globalConfiguration.UseSqlServerStorage(sqlConnectStr, mssqlOption) .UseConsole(new ConsoleOptions { BackgroundColor = "#000079" }) .UseTagsWithSql(new TagsOptions() { TagsListStyle = TagsListStyle.Dropdown }) .UseHangfireHttpJob(httpJobOptions) .UseHeartbeatPage(); }
public void Ctor_CreatesSqlServer2005Settings() { var options = new SqlServerStorageOptions { SqlServer2005Compatibility = true }; var storage = new SqlServerStorage(ConnectionUtils.GetConnectionString(), options); Assert.Equal(typeof(SqlServer2005Settings), storage.SqlServerSettings.GetType()); }
/// <summary> /// Tells the bootstrapper to use SQL Server as a job storage /// with the given options, that can be accessed using the specified /// connection string or its name. /// </summary> /// <param name="configuration">Configuration</param> /// <param name="nameOrConnectionString">Connection string or its name</param> /// <param name="options">Advanced options</param> public static SqlServerStorage UseSqlServerStorage( this IBootstrapperConfiguration configuration, string nameOrConnectionString, SqlServerStorageOptions options) { var storage = new SqlServerStorage(nameOrConnectionString, options); configuration.UseStorage(storage); return storage; }
public void Ctor_SetsTheDefaultOptions() { var options = new SqlServerStorageOptions(); Assert.True(options.QueuePollInterval > TimeSpan.Zero); #pragma warning disable 618 Assert.True(options.InvisibilityTimeout > TimeSpan.Zero); #pragma warning restore 618 Assert.True(options.JobExpirationCheckInterval > TimeSpan.Zero); Assert.True(options.PrepareSchemaIfNecessary); }
public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsEqualToZero() { var options = new SqlServerStorageOptions(); Assert.Throws<ArgumentException>( () => options.QueuePollInterval = TimeSpan.Zero); }
public void Ctor_SetsTheDefaultOptions() { var options = new SqlServerStorageOptions(); Assert.NotEqual(0, options.QueuePollInterval.TotalSeconds); Assert.True(options.PrepareSchemaIfNecessary); }
public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsNegative() { var options = new SqlServerStorageOptions(); Assert.Throws<ArgumentException>( () => options.QueuePollInterval = TimeSpan.FromSeconds(-1)); }
public void Set_QueuePollInterval_SetsTheValue() { var options = new SqlServerStorageOptions { QueuePollInterval = TimeSpan.FromSeconds(1) }; Assert.Equal(TimeSpan.FromSeconds(1), options.QueuePollInterval); }
public SqlServerStorageFacts() { _options = new SqlServerStorageOptions { PrepareSchemaIfNecessary = false }; }