【问题标题】:Stop HangFire from running a job multiple times on different servers?阻止 HangFire 在不同服务器上多次运行作业?
【发布时间】:2020-08-05 22:36:08
【问题描述】:

我设置了一个重复性工作,它只处理一些订单:

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

我遇到的问题是我们有多个“备份”服务器都在运行相同的代码。他们都在访问同一个 HangFire 数据库。

我看到同一个作业运行了多次,这显然会给我们带来错误,因为订单已经处理完毕。

我希望备份服务器能够识别重复作业已经排队,而不是再次排队。我认为这样做会脱离工作名称(上面的第一个参数)。我在这里错过了什么?

我在下面包含了 hangfire 服务器设置:

        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();
        }```

【问题讨论】:

    标签: c# hangfire


    【解决方案1】:

    不确定您是否已经尝试过,但请考虑在作业上使用 DisableConcurrentExecution 属性,以防止多次执行同一作业。

    【讨论】:

      【解决方案2】:

      由于默认值仅在进程级别提供唯一性,因此如果您想在同一进程中运行不同的服务器实例,则应手动处理:

      var options = new BackgroundJobServerOptions
      {
          ServerName = String.Format(
          "{0}.{1}",
          Environment.MachineName,
          Guid.NewGuid().ToString())
      };
      
      var server = new BackgroundJobServer(options);
      // or
      app.UseHangfireServer(options);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-15
        • 2014-08-30
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 2016-11-11
        • 2019-01-08
        相关资源
        最近更新 更多