禁用重新排队失败的Hangfire BackgroundJob

use*_*766 27 c# hangfire

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

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

use*_*766 20

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

  • 如果使用 DI 容器,则必须将属性放在接口定义上,而不是放在实现上。例如。`接口 IMyService { [AutomaticRetry(Attempts = 0)void MyMethod(); }` (6认同)
  • 您还可以添加`OnAttemptsExceeded = AttemptsExceededAction.Delete`来忽略它们,并且不要破坏“失败的作业”页面。 (2认同)

Owe*_*ing 10

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

[AutomaticRetry(Attempts = 0)]
Run Code Online (Sandbox Code Playgroud)

或者全局设置:

GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
Run Code Online (Sandbox Code Playgroud)


小智 9

今天遇到了这个问题,但想在 .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 });
        });
Run Code Online (Sandbox Code Playgroud)


Sim*_*ver 7

重要的是,如果将DI容器与接口一起使用,则必须将属性放在接口定义上

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

像这样排队工作

Hangfire.RecurringJob.AddOrUpdate<IDataUpdater>(updater => updater.UpdateData(), Cron.Hourly);
Run Code Online (Sandbox Code Playgroud)

通过在实现中抛出任何旧异常来对其进行测试。如果做对了,您会在工作历史中的“已删除”下看到它。

在此处输入图片说明


小智 5

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

BackgroundJob.Enqueue<IMyJobService>(js => js.DoWork());
Run Code Online (Sandbox Code Playgroud)

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

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

我想出的解决方案是:

public MyTestController
{
    private readonly IMyJobService _myJobService;

    public MyTestClass(IMyJobService myJobService)
    {
        _myJobService = myJobService;
    }

    public ActionResult Work()
    {
        BackgroundJob.Enqueue(() => _myJobService.DoWork());
        return Ok();
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是依靠BackgroundJob.Enqueue<T>注入我的IMyJobService实现,我自己做。基本上就是这样。我希望这会帮助某人。

  • 我解决了同样的问题,将 AutomaticRetryAttribute 放在接口的方法定义上,而不是放在实现的方法上。 (3认同)