我目前正在开发 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/