禁用失败的 Hangfire BackgroundJob 的重新排队

Disable re-queueing of failed Hangfire BackgroundJob

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

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

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

我 运行 遇到了类似的问题,我找到了解决方案。使用全局过滤器对我来说不是一个选择。我正在使用 asp.net 核心,我有一个简单的 fire and forget 后台作业。由于某种原因, 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<T> 来注入我的 IMyJobService 实现,而是我自己完成了。基本上就是这样。我希望这会对某人有所帮助。

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

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

像这样排队作业

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

通过在您的实现中抛出任何旧异常来测试它。如果你做对了,你会在 'deleted'.

下的工作历史记录中看到它

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

[AutomaticRetry(Attempts = 0)]

或者全局设置:

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

运行 今天进入这个,但想在 .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 });
        });