有没有办法禁用失败的Hangfire BackgroundJob的重新排队?
我们不希望再次执行失败的作业,因为这可能会导致问题。
答案 0 :(得分:17)
使用[AutomaticRetry(Attempts = 0)]
答案 1 :(得分:7)
如果将DI容器与接口一起使用,则必须将该属性放在接口定义上
public interface IDataUpdater
{
[Hangfire.AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
void UpdateData();
}
像这样排队工作
Hangfire.RecurringJob.AddOrUpdate<IDataUpdater>(updater => updater.UpdateData(), Cron.Hourly);
通过在您的实现中抛出任何旧异常来测试它。如果你做得对,你会在“删除”下的工作历史中看到这一点。
答案 2 :(得分:3)
我遇到了类似的问题,我找到了解决方案。使用全局过滤器对我来说不是一个选择。我使用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<T>
注入我的IMyJobService
实现,而是自己做。基本上就是这样。我希望这会对某人有所帮助。
答案 3 :(得分: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 });
});