有没有一种方法可以禁用失败的Hangfire BackgroundJob重新排队?
我们不希望再次执行失败的作业,因为这可能会导致问题。
使用[AutomaticRetry(Attempts = 0)]
解决了问题。
[AutomaticRetry(Attempts = 0)]
或者在全局范围内设置:
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
如果你使用 DI 容器和接口一起使用,你必须在接口定义上放置属性。
public interface IDataUpdater
{
[Hangfire.AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
void UpdateData();
}
将工作排入队列
Hangfire.RecurringJob.AddOrUpdate<IDataUpdater>(updater => updater.UpdateData(), Cron.Hourly);
只需在代码实现中随意抛出任何旧异常来测试它。如果您做得正确,您将在作业历史记录下看到这个异常已被“删除”。
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 });
});
我曾经遇到过类似的问题,并找到了解决方法。对我来说,使用全局过滤器不是一个选择。我正在使用asp.net core和一个简单的后台任务。由于某种原因,AutomaticRetryAttribute
被忽略了。结果发现我添加任务的方式是解决这个问题的关键。我的应用程序中有类似的代码,这是导致问题的原因:
BackgroundJob.Enqueue<IMyJobService>(js => js.DoWork());
[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
实现,而是自己实现。基本上就是这样。希望能对某些人有所帮助。
OnAttemptsExceeded = AttemptsExceededAction.Delete
来忽略这些作业并避免"失败作业"页面的异常。 - odinserjinterface IMyService { [AutomaticRetry(Attempts = 0)] void MyMethod(); }
- Simon_Weaver