Hangfire配置延迟任务过期时间如果过期
Hangfire configure delayed task expiration time if overdue
是否可以通过配置为延迟任务设置过期时间?
如果逾期,是否在配置的时间已经过去后处理它们?
我不知道 Hangfire 中存在这个功能。
但是,您可以通过创建 JobFilterAttribute
来对其进行编码,如下所示:
public class MyJobFilterAttribute : JobFilterAttribute, IElectStateFilter
{
private DateTime CreationTime { get; set; }
private int ExpirationInMinutes { get; set; }
public MyJobFilterAttribute(int expirationInMinutes)
{
this.ExpirationInMinutes = expirationInMinutes;
this.CreationTime = DateTime.Now;
}
/// <summary>
/// Election of a new state: if the new state is "enqueued" then set the queue to use
/// </summary>
/// <param name="context"></param>
public void OnStateElection(ElectStateContext context)
{
var enqueuedState = context.CandidateState as EnqueuedState;
if ((DateTime.Now - CreationTime) > new TimeSpan(0, ExpirationInMinutes, 0))
{
Hangfire.BackgroundJob.Delete(context.BackgroundJob.Id);
}
}
}
然后将属性添加到作业的目标方法中:
[MyJobFilter(5)]
public void MyJobWithExpiration() {}
public void MyCallingMethod() {
BackgroundJob.Enqueue(() => MyJobWithExpiration());
}
注:代码未测试,这是大意
是否可以通过配置为延迟任务设置过期时间? 如果逾期,是否在配置的时间已经过去后处理它们?
我不知道 Hangfire 中存在这个功能。
但是,您可以通过创建 JobFilterAttribute
来对其进行编码,如下所示:
public class MyJobFilterAttribute : JobFilterAttribute, IElectStateFilter
{
private DateTime CreationTime { get; set; }
private int ExpirationInMinutes { get; set; }
public MyJobFilterAttribute(int expirationInMinutes)
{
this.ExpirationInMinutes = expirationInMinutes;
this.CreationTime = DateTime.Now;
}
/// <summary>
/// Election of a new state: if the new state is "enqueued" then set the queue to use
/// </summary>
/// <param name="context"></param>
public void OnStateElection(ElectStateContext context)
{
var enqueuedState = context.CandidateState as EnqueuedState;
if ((DateTime.Now - CreationTime) > new TimeSpan(0, ExpirationInMinutes, 0))
{
Hangfire.BackgroundJob.Delete(context.BackgroundJob.Id);
}
}
}
然后将属性添加到作业的目标方法中:
[MyJobFilter(5)]
public void MyJobWithExpiration() {}
public void MyCallingMethod() {
BackgroundJob.Enqueue(() => MyJobWithExpiration());
}
注:代码未测试,这是大意