我目前正在开发使用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);
}
但问题是我无法找到以编程方式访问失败作业的方法。我想知道是否有人遇到过这个问题,想知道细节。
您可以使用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
如果需要捕获事件,则在应用状态后,您可以实现qazxswpoi。