【问题标题】:Disable re-queueing of failed Hangfire BackgroundJob禁用重新排队失败的 Hangfire BackgroundJob
【发布时间】:2015-03-04 08:10:22
【问题描述】:

有没有办法禁止对失败的 Hangfire BackgroundJob 重新排队?

我们不希望再次执行失败的作业,因为这可能会导致问题。

【问题讨论】:

    标签: c# hangfire


    【解决方案1】:

    已解决,使用[AutomaticRetry(Attempts = 0)]

    【讨论】:

    • 您也可以添加OnAttemptsExceeded = AttemptsExceededAction.Delete 以忽略它们并且不要炸毁“失败的作业”页面。
    • 这个解决方案是文档所说的,但在实践中,我看不出正在运行的系统有什么不同。即使此属性位于我从重复作业中调用的方法上,我失败的作业也会自行重试。其他人似乎也有same problem
    • 如果使用 DI 容器,您必须将属性放在接口定义上而不是实现上。例如。 interface IMyService { [AutomaticRetry(Attempts = 0)void MyMethod(); }
    【解决方案2】:

    您可以使用以下属性注释要在后台运行的方法:

    [AutomaticRetry(Attempts = 0)]
    

    或者全局设置:

    GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
    

    【讨论】:

    • 但是您如何逐个工作地做到这一点?假设您想通过 defualy 重试,但作业以不可恢复的方式失败,并且您不希望它重试该特定作业。
    【解决方案3】:

    重要如果使用带有接口的DI容器,必须将属性放在接口定义上

    public interface IDataUpdater
    {
        [Hangfire.AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
        void UpdateData();
    }
    

    像这样排队工作

    Hangfire.RecurringJob.AddOrUpdate<IDataUpdater>(updater => updater.UpdateData(), Cron.Hourly);
    

    只需在您的实现中抛出任何旧异常即可对其进行测试。如果您操作正确,您会在“已删除”下的工作历史记录中看到这一点。

    【讨论】:

      【解决方案4】:

      我遇到了类似的问题,我找到了解决方案。使用全局过滤器对我来说不是一个选项。我正在使用 asp.net 核心,我有一个简单的火灾和忘记后台工作。出于某种原因,AutomaticRetryAttribute 被忽略了。事实证明,我添加工作的方式是我解决方案的关键。我的应用中有一个类似的代码导致了这个问题:

      BackgroundJob.Enqueue<IMyJobService>(js => js.DoWork());
      

      在我的 IMyJobService 实现中,我有以下代码:

      [AutomaticRetry(Attempts = 0)]
      public void DoWork()
      {
          // I'm working hard here
      }
      

      我想出的解决方案是:

      public MyTestController
      {
          private readonly IMyJobService _myJobService;
      
          public MyTestClass(IMyJobService myJobService)
          {
              _myJobService = myJobService;
          }
      
          public ActionResult Work()
          {
              BackgroundJob.Enqueue(() => _myJobService.DoWork());
              return Ok();
          }
      }
      

      我不是依靠BackgroundJob.Enqueue&lt;T&gt; 来注入我的IMyJobService 实现,而是自己做。基本上就是这样。我希望这会对某人有所帮助。

      【讨论】:

      • 我解决了同样的问题,将 AutomaticRetryAttribute 放在接口的方法定义上,而不是在实现的方法定义上。
      【解决方案5】:

      今天遇到了这个问题,但想在 .NET API 应用程序中全局设置重试过滤器。

      以下工作...

      services.AddHangfire(configuration => {
                  // Disable retry for failed jobs
                  // https://docs.hangfire.io/en/latest/background-processing/dealing-with-exceptions.html?highlight=retry
                  configuration.UseFilter(new AutomaticRetryAttribute { Attempts = 0 });
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 2022-10-13
        • 1970-01-01
        相关资源
        最近更新 更多