【问题标题】:How to access Failed Hangfire Jobs如何访问失败的 Hangfire 作业
【发布时间】:2016-05-25 18:46:18
【问题描述】:

我目前正在开发已开始使用hangfire 的EmailNotification 模块。唯一的问题是在尝试 10 次之后,如果在我的情况下 hangfire 未能(安排工作)电子邮件,我无法找到通过代码获取有关该更新的方法。

我知道,我可以通过如下配置hangfire来访问hangfire - 仪表板:

public void ConfigureHangfire(IAppBuilder app)
{
    var container = AutofacConfig.RegisterBackgroundJobComponents();
    var sqlOptions = new SqlServerStorageOptions
    {
        PrepareSchemaIfNecessary = Config.CreateHangfireSchema
    };
    Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("hangfire", sqlOptions);
    Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(container);
    var options = new BackgroundJobServerOptions() {Queues = new[] {"emails"}};
    app.UseHangfireDashboard();
    app.UseHangfireServer(options);
}

但问题是我无法找到以编程方式访问失败作业的方法。不知道有没有人遇到过这个问题,想详细了解一下。

【问题讨论】:

  • 在这里尝试:docs.hangfire.io/en/latest/background-processing/… 查找“我们可以创建自定义异常处理程序”。也许这会有所帮助。我没有给出这个答案,因为我不确定。
  • 基于自定义异常访问失败作业的逻辑,我不确定我是否喜欢这个想法。但是,我正在研究它 - 如果我发现一些方便的东西 - 会在这里更新 - 谢谢!

标签: c# asp.net rest asynchronous hangfire


【解决方案1】:

您可以为此使用 Hangfire 作业过滤器。作业过滤器允许你扩展hangfire的功能,你可以用它们做很多有趣的事情 (详见官方文档here

创建一个从JobFilterAttribute扩展的类

然后实现IElectStateFilter接口。该接口为您提供了一个方法,OnStateElection,当作业的当前状态被更改为指定的候选状态时调用,例如FailedState

public class MyCustomFilter : JobFilterAttribute, IElectStateFilter
{
    public void IElectStateFilter.OnStateElection(ElectStateContext context)
    {
        var failedState = context.CandidateState as FailedState;
        if (failedState != null)
        {
            //Job has failed
            //Job ID => context.BackgroundJob.Id,
            //Exception => failedState.Exception
        }
    }
}

然后,注册这个属性 -

GlobalJobFilters.Filters.Add(new MyCustomFiler());

如果需要捕获事件,应用状态后,可以实现IApplyStateFilter代替。

【讨论】:

  • 谢谢 - 成功了!!唯一的事情是它是异步的,所以我不会立即知道在 UI 上显示什么 - 但我想,现在我只使用三种不同的状态,比如 - 进行中 - 完成 - 失败 - 直到我确认完成或失败,我将使用 IN PROGRESS 作为该工作的状态!
  • 在hangfire 1.6.x 中,我体验到OnStateElection 会说failed,即使重试计数尚未完全耗尽。不确定这是否是设计使然,但出于我的目的(在实际失败时通知并且不再重试)IApplyStateFilter 做到了。
猜你喜欢
  • 1970-01-01
  • 2022-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
相关资源
最近更新 更多