我目前正在开发EmailNotification模块,其中我已经开始使用hangfire。唯一的问题是,在尝试了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);
}但问题是,我不能找到一种方法来通过编程访问失败的作业。我想知道有没有人遇到过这个问题,想知道细节。
发布于 2016-05-26 14:03:47
为此,您可以使用Hangfire作业筛选器。Job filter允许你扩展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。
https://stackoverflow.com/questions/37445301
复制相似问题