c# - 如何访问失败的 Hangfire 作业

标签 c# asp.net rest asynchronous hangfire

我目前正在开发 EmailNotification 模块,我已经开始在其中使用 hangfire。唯一的问题是在尝试 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);
}

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

最佳答案

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

创建一个从 JobFilterAttribute 扩展的类

然后实现IElectStateFilter接口(interface)。此接口(interface)为您提供了一个方法,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

关于c# - 如何访问失败的 Hangfire 作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37445301/

相关文章:

c# - 尝试 NHibernate 事务时捕获 SqlException

php - Yii2 rest api getBodyParams() 无法从 PUT 请求中获取参数

rest - REST 只能使用 HTTP 来实现还是也可以使用其他东西?

rest - 如何开发 Spring Data REST 应用程序?

c# - Visual Studio 显示 ReSharper 的 'Configure settings to improve performance' 通知

c# - ASP.NET Core Html Helper 使用 TagBuilder 渲染原始文本而不是格式化 HTML

c# - 如何处理多线程中的竞争条件?

c# - 在 TFS 中,如何使用查询 (C#) 查找测试套件中的所有测试用例?

asp.net - AspNetSession 布局渲染器不起作用

asp.net - 消除临时 ASP.Net 文件