【发布时间】:2015-03-04 08:10:22
【问题描述】:
有没有办法禁止对失败的 Hangfire BackgroundJob 重新排队?
我们不希望再次执行失败的作业,因为这可能会导致问题。
【问题讨论】:
有没有办法禁止对失败的 Hangfire BackgroundJob 重新排队?
我们不希望再次执行失败的作业,因为这可能会导致问题。
【问题讨论】:
已解决,使用[AutomaticRetry(Attempts = 0)]
【讨论】:
OnAttemptsExceeded = AttemptsExceededAction.Delete 以忽略它们并且不要炸毁“失败的作业”页面。
interface IMyService { [AutomaticRetry(Attempts = 0)void MyMethod(); }
您可以使用以下属性注释要在后台运行的方法:
[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);
只需在您的实现中抛出任何旧异常即可对其进行测试。如果您操作正确,您会在“已删除”下的工作历史记录中看到这一点。
【讨论】:
我遇到了类似的问题,我找到了解决方案。使用全局过滤器对我来说不是一个选项。我正在使用 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 实现,而是自己做。基本上就是这样。我希望这会对某人有所帮助。
【讨论】:
今天遇到了这个问题,但想在 .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 });
});
【讨论】: