public Worker(JobStorage storage, WorkerContext context) { _storage = storage; _context = context; _logger = LogManager.GetLogger(String.Format("HangFire.Worker.{0}", context.WorkerNumber)); }
public StateMachineFactory(JobStorage storage) { if (storage == null) throw new ArgumentNullException("storage"); _handlers = new StateHandlerCollection(); _handlers.AddRange(GlobalStateHandlers.Handlers); _handlers.AddRange(storage.GetStateHandlers()); }
private static StateHandlerCollection GetStateHandlers(JobStorage storage) { var stateHandlers = new StateHandlerCollection(); stateHandlers.AddRange(GlobalStateHandlers.Handlers); stateHandlers.AddRange(storage.GetStateHandlers()); return stateHandlers; }
public ServerWatchdog(JobStorage storage, ServerWatchdogOptions options) { if (storage == null) throw new ArgumentNullException("storage"); if (options == null) throw new ArgumentNullException("options"); _storage = storage; _options = options; }
public ServerHeartbeat(JobStorage storage, string serverId) { if (storage == null) throw new ArgumentNullException("storage"); if (serverId == null) throw new ArgumentNullException("serverId"); _storage = storage; _serverId = serverId; }
public SqlServerConnection(JobStorage storage, SqlConnection connection) { if (storage == null) throw new ArgumentNullException("storage"); if (connection == null) throw new ArgumentNullException("connection"); _connection = connection; Storage = storage; }
public FetchedJobsWatcher( JobStorage storage, FetchedJobsWatcherOptions options) { if (storage == null) throw new ArgumentNullException("storage"); if (options == null) throw new ArgumentNullException("options"); _storage = storage; _options = options; }
public FetchedJobsWatcher(JobStorage storage, FetchedJobsWatcherOptions options) { if (storage == null) throw new ArgumentNullException("storage"); if (options == null) throw new ArgumentNullException("options"); if (options.InvisibilityTimeout.Ticks <= 0) { throw new ArgumentOutOfRangeException("invisibilityTimeout", "Invisibility timeout duration should be positive."); } _storage = storage; _options = options; }
public SchedulePoller( JobStorage storage, IStateMachineFactory stateMachineFactory, TimeSpan pollInterval) { if (storage == null) throw new ArgumentNullException("storage"); if (stateMachineFactory == null) throw new ArgumentNullException("stateMachineFactory"); _storage = storage; _stateMachineFactory = stateMachineFactory; _pollInterval = pollInterval; }
public RecurringJobScheduler( [NotNull] JobStorage storage, [NotNull] IBackgroundJobClient client, [NotNull] IDateTimeProvider dateTimeProvider) { if (storage == null) throw new ArgumentNullException("storage"); if (client == null) throw new ArgumentNullException("client"); if (dateTimeProvider == null) throw new ArgumentNullException("dateTimeProvider"); _storage = storage; _client = client; _dateTimeProvider = dateTimeProvider; }
public static void MapHangfireDashboard( [NotNull] this IAppBuilder app, string dashboardPath, IEnumerable<IAuthorizationFilter> authorizationFilters, JobStorage storage) { if (app == null) throw new ArgumentNullException("app"); app.Map(dashboardPath, subApp => subApp.Use<DashboardMiddleware>( storage, DashboardRoutes.Routes, authorizationFilters)); }
public WorkerManager(JobStorage storage, ServerContext context, int workerCount) { _workers = new DisposableCollection<Worker>(); for (var i = 1; i <= workerCount; i++) { var workerContext = new WorkerContext(context, i); var worker = new Worker(storage, workerContext); worker.Start(); _workers.Add(worker); } }
public DashboardMiddleware( OwinMiddleware next, [NotNull] JobStorage storage, [NotNull] RouteCollection routes, [NotNull] IEnumerable<IAuthorizationFilter> authorizationFilters) : base(next) { if (storage == null) throw new ArgumentNullException("storage"); if (routes == null) throw new ArgumentNullException("routes"); if (authorizationFilters == null) throw new ArgumentNullException("authorizationFilters"); _storage = storage; _routes = routes; _authorizationFilters = authorizationFilters; }
public RecurringJobScheduler( [NotNull] JobStorage storage, [NotNull] IBackgroundJobClient client, [NotNull] IScheduleInstantFactory instantFactory, [NotNull] IThrottler throttler) { if (storage == null) throw new ArgumentNullException("storage"); if (client == null) throw new ArgumentNullException("client"); if (instantFactory == null) throw new ArgumentNullException("instantFactory"); if (throttler == null) throw new ArgumentNullException("throttler"); _storage = storage; _client = client; _instantFactory = instantFactory; _throttler = throttler; }
public ServerBootstrapper( string serverId, ServerContext context, JobStorage storage, Lazy<IServerSupervisor> supervisorFactory) { if (storage == null) throw new ArgumentNullException("storage"); if (serverId == null) throw new ArgumentNullException("serverId"); if (context == null) throw new ArgumentNullException("context"); if (supervisorFactory == null) throw new ArgumentNullException("supervisorFactory"); _storage = storage; _serverId = serverId; _context = context; _supervisorFactory = supervisorFactory; }
public Worker( [NotNull] WorkerContext context, [NotNull] JobStorage storage, [NotNull] IJobPerformanceProcess process, [NotNull] IStateMachineFactory stateMachineFactory) { if (context == null) throw new ArgumentNullException("context"); if (storage == null) throw new ArgumentNullException("storage"); if (process == null) throw new ArgumentNullException("process"); if (stateMachineFactory == null) throw new ArgumentNullException("stateMachineFactory"); _context = context; _storage = storage; _process = process; _stateMachineFactory = stateMachineFactory; }
public AspNetCoreDashboardMiddleware( [NotNull] RequestDelegate next, [NotNull] JobStorage storage, [NotNull] DashboardOptions options, [NotNull] RouteCollection routes) { if (next == null) throw new ArgumentNullException(nameof(next)); if (storage == null) throw new ArgumentNullException(nameof(storage)); if (options == null) throw new ArgumentNullException(nameof(options)); if (routes == null) throw new ArgumentNullException(nameof(routes)); _next = next; _storage = storage; _options = options; _routes = routes; }
public DashboardMiddleware( OwinMiddleware next, string appPath, int statsPollingInterval, [NotNull] JobStorage storage, [NotNull] RouteCollection routes, [NotNull] IEnumerable<IAuthorizationFilter> authorizationFilters) : base(next) { if (storage == null) throw new ArgumentNullException(nameof(storage)); if (routes == null) throw new ArgumentNullException(nameof(routes)); if (authorizationFilters == null) throw new ArgumentNullException(nameof(authorizationFilters)); _appPath = appPath; _statsPollingInterval = statsPollingInterval; _storage = storage; _routes = routes; _authorizationFilters = authorizationFilters; }
public ServerBootstrapper( string serverId, ServerContext context, JobStorage storage, Lazy<IServerSupervisor> supervisorFactory) { if (storage == null) throw new ArgumentNullException("storage"); if (serverId == null) throw new ArgumentNullException("serverId"); if (context == null) throw new ArgumentNullException("context"); if (supervisorFactory == null) throw new ArgumentNullException("supervisorFactory"); _storage = storage; _serverId = serverId; _context = context; _supervisorFactory = supervisorFactory; if (!RunningWithMono()) { _globalMutex = new Mutex (false, String.Format (@"Global\{0}_{1}", BootstrapperId, _serverId)); } }
internal SharedWorkerContext( string serverId, string[] queues, JobStorage storage, IJobPerformanceProcess performanceProcess, JobActivator activator, IStateMachineFactory stateMachineFactory) { if (serverId == null) throw new ArgumentNullException("serverId"); if (queues == null) throw new ArgumentNullException("queues"); if (storage == null) throw new ArgumentNullException("storage"); if (performanceProcess == null) throw new ArgumentNullException("performanceProcess"); if (activator == null) throw new ArgumentNullException("activator"); if (stateMachineFactory == null) throw new ArgumentNullException("stateMachineFactory"); ServerId = serverId; Queues = queues; Storage = storage; PerformanceProcess = performanceProcess; Activator = activator; StateMachineFactory = stateMachineFactory; }
public JobServer( JobStorage storage, string serverName, int workerCount, IEnumerable<string> queues) { _storage = storage; _workerCount = workerCount; _queues = queues; if (queues == null) throw new ArgumentNullException("queues"); _context = new ServerContext( serverName, _queues, new JobPerformancePipeline()); _serverThread = new Thread(RunServer) { Name = typeof(JobServer).Name, IsBackground = true }; _serverThread.Start(); }
/// <summary> /// Configures Hangfire to use Tags. /// </summary> /// <param name="configuration">Global configuration</param> /// <param name="options">Options for tags</param> /// <param name="sqlOptions">Options for sql storage</param> /// <param name="jobStorage">The jobStorage for which this configuration is used.</param> /// <returns></returns> public static IGlobalConfiguration UseTagsWithSQLite(this IGlobalConfiguration configuration, TagsOptions options = null, SQLiteStorageOptions sqlOptions = null, JobStorage jobStorage = null) { options = options ?? new TagsOptions(); sqlOptions = sqlOptions ?? new SQLiteStorageOptions(); var storage = new SQLiteTagsServiceStorage(sqlOptions); (jobStorage ?? JobStorage.Current).Register(options, storage); var config = configuration.UseTags(options); return(config); }
/// <summary> /// Tells bootstrapper to start a job server with the given /// options that use the specified storage (not the global one) on /// application start and stop it automatically on application /// shutdown request. /// </summary> /// <param name="configuration">Configuration</param> /// <param name="storage">Job storage to use</param> /// <param name="options">Job server options</param> public static void UseServer( this IBootstrapperConfiguration configuration, JobStorage storage, BackgroundJobServerOptions options) { configuration.UseServer(() => new BackgroundJobServer(options, storage)); }
public RecurringDateRangeJobManager([NotNull] JobStorage storage) : this(storage, new BackgroundJobFactory()) { }
public HangfireJobServer(JobStorage storage) { _server = new BackgroundJobServer(storage); }
private IApplicationBuilder UseHangfireDashboard(IApplicationBuilder app, string pathMatch = "/hangfire", DashboardOptions options = null, JobStorage storage = null) { var services = app.ApplicationServices; storage = storage ?? services.GetRequiredService <JobStorage>(); options = options ?? services.GetService <DashboardOptions>() ?? new DashboardOptions(); var routes = app.ApplicationServices.GetRequiredService <RouteCollection>(); //use our custom middleware app.Map(new PathString(pathMatch), x => x.UseMiddleware <CustomHangfireDashboardMiddleware>(storage, options, routes)); return(app); }
public override int GetJobCount(JobStorage jobStorage, string[] tags, string stateName = null) { var monitoringApi = GetMonitoringApi(jobStorage); return(monitoringApi.UseConnection(redis => GetJobCount(redis, tags, stateName))); }
internal RedisTagsMonitoringApi GetMonitoringApi(JobStorage jobStorage) { return(new RedisTagsMonitoringApi(jobStorage.GetMonitoringApi(), _options)); }
private void TryScheduleJob( JobStorage storage, IStorageConnection connection, string recurringJobId, IReadOnlyDictionary<string, string> recurringJob) { var serializedJob = JobHelper.FromJson<InvocationData>(recurringJob["Job"]); var job = serializedJob.Deserialize(); var cron = recurringJob["Cron"]; var cronSchedule = CrontabSchedule.Parse(cron); try { var timeZone = recurringJob.ContainsKey("TimeZoneId") ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"]) : TimeZoneInfo.Utc; var nowInstant = _instantFactory(cronSchedule, timeZone); var changedFields = new Dictionary<string, string>(); var lastInstant = GetLastInstant(recurringJob, nowInstant); if (nowInstant.GetNextInstants(lastInstant).Any()) { var state = new EnqueuedState { Reason = "Triggered by recurring job scheduler" }; if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"])) { state.Queue = recurringJob["Queue"]; } var context = new CreateContext(storage, connection, job, state); context.Parameters["RecurringJobId"] = recurringJobId; var backgroundJob = _factory.Create(context); var jobId = backgroundJob?.Id; if (String.IsNullOrEmpty(jobId)) { Logger.Debug($"Recurring job '{recurringJobId}' execution at '{nowInstant.NowInstant}' has been canceled."); } changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant)); changedFields.Add("LastJobId", jobId ?? String.Empty); } // Fixing old recurring jobs that doesn't have the CreatedAt field if (!recurringJob.ContainsKey("CreatedAt")) { changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant)); } changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null); connection.SetRangeInHash( $"recurring-job:{recurringJobId}", changedFields); } #if NETFULL catch (TimeZoneNotFoundException ex) { #else catch (Exception ex) { // https://github.com/dotnet/corefx/issues/7552 if (!ex.GetType().Name.Equals("TimeZoneNotFoundException")) throw; #endif Logger.ErrorException( $"Recurring job '{recurringJobId}' was not triggered: {ex.Message}.", ex); } }
public BackgroundService(IWikiCacheRepository wikiCache, IModCacheRepository modCache, JobStorage hangfireStorage) { BackgroundService.WikiCache = wikiCache; BackgroundService.ModCache = modCache; }
public static JobStorageConnection GetJobStorageConnection(this JobStorage jobStorage) => (JobStorageConnection)jobStorage.GetConnection();
/// <summary> /// Starts the hangfire server. Better to use AddHangfireServer. /// </summary> public static IApplicationBuilder UseHangfireServer(this IApplicationBuilder builder, string serverName, IEnumerable <IBackgroundProcess> additionalProcesses = null, JobStorage storage = null) { //each microserver has its own queue. Queue by using the Queue attribute. //https://discuss.hangfire.io/t/one-queue-for-the-whole-farm-and-one-queue-by-server/490 var options = new BackgroundJobServerOptions { ServerName = serverName //Queues = new[] { serverName, EnqueuedState.DefaultQueue } }; if (!string.IsNullOrEmpty(options.ServerName) && !options.Queues.Contains(options.ServerName)) { var queues = options.Queues.ToList(); queues.Insert(0, options.ServerName); options.Queues = queues.ToArray(); } //https://discuss.hangfire.io/t/one-queue-for-the-whole-farm-and-one-queue-by-server/490/3 builder.UseHangfireServer(options, additionalProcesses, storage); return(builder); }
/// <summary> /// Exposes hangfire dashboard. /// </summary> public static IApplicationBuilder UseHangfireDashboard(this IApplicationBuilder builder, string route = "/hangfire", Action <DashboardOptions> configAction = null, JobStorage storage = null) { var options = new DashboardOptions { //must be set otherwise only local access allowed //Authorization = new[] { new HangfireRoleAuthorizationfilter() }, AppPath = route.Replace("/hangfire", "") }; if (configAction != null) { configAction(options); } builder.UseHangfireDashboard(route, options, storage); return(builder); }
public SchedulePoller(JobStorage storage, TimeSpan pollInterval) { _storage = storage; _pollInterval = pollInterval; }
private void TryScheduleJob( JobStorage storage, IStorageConnection connection, string recurringJobId, IReadOnlyDictionary<string, string> recurringJob) { var serializedJob = JobHelper.FromJson<InvocationData>(recurringJob["Job"]); var job = serializedJob.Deserialize(); var cron = recurringJob["Cron"]; var cronSchedule = CrontabSchedule.Parse(cron); try { var timeZone = recurringJob.ContainsKey("TimeZoneId") ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"]) : TimeZoneInfo.Utc; var nowInstant = _instantFactory(cronSchedule, timeZone); var changedFields = new Dictionary<string, string>(); var lastInstant = GetLastInstant(recurringJob, nowInstant); if (nowInstant.GetNextInstants(lastInstant).Any()) { var state = new EnqueuedState { Reason = "Triggered by recurring job scheduler" }; if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"])) { state.Queue = recurringJob["Queue"]; } var backgroundJob = _factory.Create(new CreateContext(storage, connection, job, state)); var jobId = backgroundJob != null ? backgroundJob.Id : null; if (String.IsNullOrEmpty(jobId)) { Logger.DebugFormat( "Recurring job '{0}' execution at '{1}' has been canceled.", recurringJobId, nowInstant.NowInstant); } changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant)); changedFields.Add("LastJobId", jobId ?? String.Empty); } // Fixing old recurring jobs that doesn't have the CreatedAt field if (!recurringJob.ContainsKey("CreatedAt")) { changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant)); } changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null); connection.SetRangeInHash( String.Format("recurring-job:{0}", recurringJobId), changedFields); } catch (TimeZoneNotFoundException ex) { Logger.ErrorException( String.Format("Recurring job '{0}' was not triggered: {1}.", recurringJobId, ex.Message), ex); } }
public CrmETagAttribute() { _metrics = new MetricService(); _hangfireJobStorage = JobStorage.Current; _env = new Env(); }
public RedisConnection(JobStorage storage, IRedisClient redis) { _redis = redis; Storage = storage; }
public CrmETagAttribute(JobStorage hangfireJobStorage, IMetricService metrics, IEnv env) { _hangfireJobStorage = hangfireJobStorage; _metrics = metrics; _env = env; }
public ServerWatchdog(JobStorage storage) : this(storage, new ServerWatchdogOptions()) { }
public TagExpirationTransaction(JobStorage jobStorage, JobStorageTransaction transaction) : this(new TagsStorage(jobStorage), transaction) { }
/// <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); }
public CustomBackgroundJobServer([NotNull] BackgroundJobServerOptions options, [NotNull] JobStorage storage) : this(options, storage, Enumerable.Empty <IBackgroundProcess>()) { }
public FetchedJobsWatcher(JobStorage storage) : this(storage, new FetchedJobsWatcherOptions()) { }
public RecurringDateRangeJobManager([NotNull] JobStorage storage, [NotNull] IBackgroundJobFactory factory) { _storage = storage ?? throw new ArgumentNullException(nameof(storage)); _factory = factory ?? throw new ArgumentNullException(nameof(factory)); }
public BackgroundJobClientWithContext([NotNull] JobStorage storage, [NotNull] IJobFilterProvider filterProvider) : this(storage, new BackgroundJobFactory(filterProvider), new BackgroundJobStateChanger(filterProvider)) { }
public HangfireMonitorService(JobStorage hangfireJobStorage) { _hangfireJobStorage = hangfireJobStorage; }
public MIFCoreRecurringJobManager(JobStorage jobStorage) { this.recurringJobManager = new RecurringJobManager(jobStorage); this.jobStorage = jobStorage; }
public static void Register(this JobStorage jobStorage, TagsOptions options, ITagsServiceStorage serviceStorage) { StorageRegistration.Register(jobStorage, options, serviceStorage); }
public CustomBackgroundJobServer([NotNull] JobStorage storage) : this(new BackgroundJobServerOptions(), storage) { }
private void TryScheduleJob( JobStorage storage, IStorageConnection connection, string recurringJobId, IReadOnlyDictionary <string, string> recurringJob) { // If a recurring job has the "V" field, then it was created by a newer // version. Despite we can handle 1.7.0-based recurring jobs just fine, // future versions may introduce new features anyway, so it's safer to // let other servers to handle this recurring job. if (recurringJob.ContainsKey("V")) { return; } var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]); var job = serializedJob.Deserialize(); var cron = recurringJob["Cron"]; var cronSchedule = CrontabSchedule.Parse(cron); try { var timeZone = recurringJob.ContainsKey("TimeZoneId") ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"]) : TimeZoneInfo.Utc; var nowInstant = _instantFactory(cronSchedule, timeZone); var changedFields = new Dictionary <string, string>(); var lastInstant = GetLastInstant(recurringJob, nowInstant); if (nowInstant.GetNextInstants(lastInstant).Any()) { var state = new EnqueuedState { Reason = "Triggered by recurring job scheduler" }; if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"])) { state.Queue = recurringJob["Queue"]; } var context = new CreateContext(storage, connection, job, state, _profiler); context.Parameters["RecurringJobId"] = recurringJobId; var backgroundJob = _factory.Create(context); var jobId = backgroundJob?.Id; if (String.IsNullOrEmpty(jobId)) { _logger.Debug($"Recurring job '{recurringJobId}' execution at '{nowInstant.NowInstant}' has been canceled."); } changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant)); changedFields.Add("LastJobId", jobId ?? String.Empty); } // Fixing old recurring jobs that doesn't have the CreatedAt field if (!recurringJob.ContainsKey("CreatedAt")) { changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant)); } changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null); connection.SetRangeInHash( $"recurring-job:{recurringJobId}", changedFields); } #if NETFULL catch (TimeZoneNotFoundException ex) { #else catch (Exception ex) { // https://github.com/dotnet/corefx/issues/7552 if (!ex.GetType().Name.Equals("TimeZoneNotFoundException")) { throw; } #endif _logger.ErrorException( $"Recurring job '{recurringJobId}' was not triggered: {ex.Message}.", ex); } }
public BackgroundProcessingServer( [NotNull] JobStorage storage, [NotNull] IEnumerable <IBackgroundProcess> processes) : this(storage, processes, new Dictionary <string, object>()) { }
public FetchedJobsWatcher(JobStorage storage, TimeSpan invisibilityTimeout) : this(storage, invisibilityTimeout, new FetchedJobsWatcherOptions()) { }
private void TryScheduleJob( JobStorage storage, IStorageConnection connection, string recurringJobId, IReadOnlyDictionary <string, string> recurringJob) { var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]); var job = serializedJob.Deserialize(); var cron = recurringJob["Cron"]; var cronSchedule = CrontabSchedule.Parse(cron); try { var timeZone = recurringJob.ContainsKey("TimeZoneId") ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"]) : TimeZoneInfo.Utc; var nowInstant = _instantFactory(cronSchedule, timeZone); var changedFields = new Dictionary <string, string>(); var lastInstant = GetLastInstant(recurringJob, nowInstant); if (nowInstant.GetNextInstants(lastInstant).Any()) { var state = new EnqueuedState { Reason = "Triggered by recurring job scheduler" }; if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"])) { state.Queue = recurringJob["Queue"]; } var backgroundJob = _factory.Create(new CreateContext(storage, connection, job, state)); var jobId = backgroundJob != null ? backgroundJob.Id : null; if (String.IsNullOrEmpty(jobId)) { Logger.DebugFormat( "Recurring job '{0}' execution at '{1}' has been canceled.", recurringJobId, nowInstant.NowInstant); } changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant)); changedFields.Add("LastJobId", jobId ?? String.Empty); } // Fixing old recurring jobs that doesn't have the CreatedAt field if (!recurringJob.ContainsKey("CreatedAt")) { changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant)); } changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null); connection.SetRangeInHash( String.Format("recurring-job:{0}", recurringJobId), changedFields); } catch (TimeZoneNotFoundException ex) { Logger.ErrorException( String.Format("Recurring job '{0}' was not triggered: {1}.", recurringJobId, ex.Message), ex); } }
private void InitializeHangFire() { JobStorage.Current = new SqlServerStorage(_hangFireConfiguration.HangFireConnectionString); _jobStorageCurrent = JobStorage.Current; }
private void TryScheduleJob( JobStorage storage, IStorageConnection connection, string recurringJobId, IReadOnlyDictionary<string, string> recurringJob) { var serializedJob = JobHelper.FromJson<InvocationData>(recurringJob["Job"]); var job = serializedJob.Deserialize(); var cron = recurringJob["Cron"]; var parts = cron.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var cronSchedule = CrontabSchedule.Parse(cron, new CrontabSchedule.ParseOptions { IncludingSeconds = (parts.Length >= 6) }); try { var timeZone = recurringJob.ContainsKey("TimeZoneId") ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"]) : TimeZoneInfo.Utc; var instant = _instantFactory(cronSchedule, timeZone); var lastExecutionTime = recurringJob.ContainsKey("LastExecution") ? JobHelper.DeserializeDateTime(recurringJob["LastExecution"]) : (DateTime?)null; var changedFields = new Dictionary<string, string>(); if (instant.GetNextInstants(lastExecutionTime).Any()) { var state = new EnqueuedState { Reason = "Triggered by recurring job scheduler" }; if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"])) { state.Queue = recurringJob["Queue"]; } var backgroundJob = _factory.Create(new CreateContext(storage, connection, job, state)); var jobId = backgroundJob != null ? backgroundJob.Id : null; if (String.IsNullOrEmpty(jobId)) { Logger.DebugFormat( "Recurring job '{0}' execution at '{1}' has been canceled.", recurringJobId, instant.NowInstant); } changedFields.Add("LastExecution", JobHelper.SerializeDateTime(instant.NowInstant)); changedFields.Add("LastJobId", jobId ?? String.Empty); } changedFields.Add("NextExecution", JobHelper.SerializeDateTime(instant.NextInstant)); connection.SetRangeInHash( String.Format("recurring-job:{0}", recurringJobId), changedFields); } catch (TimeZoneNotFoundException ex) { Logger.ErrorException( String.Format("Recurring job '{0}' was not triggered: {1}.", recurringJobId, ex.Message), ex); } }
/// <summary> /// Configures Hangfire to use Tags. /// </summary> /// <param name="configuration">Global configuration</param> /// <param name="options">Options for tags</param> /// <param name="redisOptions">Options for Redis storage</param> /// <param name="jobStorage">The jobStorage for which this configuration is used.</param> /// <returns></returns> public static IGlobalConfiguration UseTagsWithRedis(this IGlobalConfiguration configuration, TagsOptions options = null, RedisStorageOptions redisOptions = null, JobStorage jobStorage = null) { options = options ?? new TagsOptions(); redisOptions = redisOptions ?? new RedisStorageOptions(); var storage = new RedisTagsServiceStorage(redisOptions); (jobStorage ?? JobStorage.Current).Register(options, storage); var config = configuration.UseTags(options).UseFilter(new RedisStateFilter(storage)); return(config); }
public BackgroundJobClientWithContext([NotNull] JobStorage storage) : this(storage, JobFilterProviders.Providers) { }