Search code examples
c#hangfire

Stop HangFire from running a job multiple times on different servers?


I have set up a recurring job that simply processes some orders:

                    {
                        RecurringJob.AddOrUpdate(
                            hangFireJob.JobId,
                            () => hangFireJob.Execute(),
                            hangFireJob.Schedule);
                    }

The issue I'm running into, is that we have multiple "backup" servers all running this same code. They all are reaching out to the same HangFire database.

I'm seeing the same job ran multiple times, which obviously gives us errors since the orders are already processed.

I want the backup servers to recognize that the recurring job has already been queued and not queue it again. I figured that it would go off the jobname to do this (the first parameter above). What am I missing here?

I included the hangfire server setup below:

        private IEnumerable<IDisposable> GetHangfireServers()
        {
            var configSettings = new Settings();
            GlobalConfiguration.Configuration
                               .UseNinjectActivator(_kernel)
                               .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                               .UseSimpleAssemblyNameTypeSerializer()
                               .UseRecommendedSerializerSettings()
                               .UseSqlServerStorage(configSettings.HangfireConnectionString, new SqlServerStorageOptions
                               {
                                   CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                                   SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                                   QueuePollInterval = TimeSpan.Zero,
                                   UseRecommendedIsolationLevel = true,
                                   DisableGlobalLocks = false,
                                   SchemaName = "LuxAdapter",
                                   PrepareSchemaIfNecessary = false
                               });

            yield return new BackgroundJobServer();
        }```

Solution

  • Not sure if you have tried this already but look into using the DisableConcurrentExecution attribute on the job that will prevent multiple executions of the same job.