如何访问失败的Hangfire作业

vra*_*ran 7 c# asp.net rest asynchronous hangfire

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

我知道这个事实,我可以通过配置hangfire来访问hangfire - dashboard,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

但问题是我无法找到以编程方式访问失败作业的方法.我想知道是否有人遇到过这个问题,想知道细节.

Yog*_*ogi 8

您可以使用Hangfire作业过滤器.作业过滤器允许您扩展hangfire的功能,并且您可以使用它们执行许多有意义的事情(有关详细信息,请参阅此处的官方文档)

创建一个扩展自的类 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,注册此属性 -

GlobalJobFilters.Filters.Add(new MyCustomFiler());
Run Code Online (Sandbox Code Playgroud)

如果需要捕获事件,则在应用状态后,您可以实现IApplyStateFilter.