如何让 Hangfire 挑选最后一小时排队的工作?
How do I make Hangfire pick jobs queued in the last hour?
我的要求是只处理最新的作业而忽略旧的作业。如何在 Hangfire 中配置它?
我已尝试使用 IApplyStateFilter 设置 ExpirationAttribute
public class ExpirationAttribute : JobFilterAttribute, IApplyStateFilter
{
private int _hours;
public ExpirationAttribute(int hours)
{
_hours = hours;
}
public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
context.JobExpirationTimeout = TimeSpan.FromHours(_hours);
}
public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
context.JobExpirationTimeout = TimeSpan.FromHours(_hours);
}
}
你可以做类似的事情:
public class ExpirationAttribute : JobFilterAttribute, IElectStateFilter
{
private int _hours;
public ExpirationAttribute(int hours)
{
_hours = hours;
}
public void OnStateElection(ElectStateContext context)
{
var processing = context.CandidateState as ProcessingState;
if (processing == null)
{
return;
}
if (DateTime.UtcNow - context.BackgroundJob.CreatedAt > TimeSpan.FromHours(_hours))
{
context.CandidateState = new SucceededState(new { }, 0, 0) { Reason = "Execution skipped due to expiration." };
}
}
}
它只是将作业过期后移至成功,而不是处理它们。我根本没有测试过,但大体上应该是正确的。
另一个选项(或者可能作为故障保护机制)是在作业启动时检查作业的创建日期时间。缺点是作业将排队并标记为已完成。
public static void MyJob(PerformContext context)
{
if (DateTime.Now.Subtract(context.BackgroundJob.CreatedAt).TotalHours >= 1)
{
// Job is older than 1 hour
return;
}
// Process job...
}
我的要求是只处理最新的作业而忽略旧的作业。如何在 Hangfire 中配置它?
我已尝试使用 IApplyStateFilter 设置 ExpirationAttribute
public class ExpirationAttribute : JobFilterAttribute, IApplyStateFilter
{
private int _hours;
public ExpirationAttribute(int hours)
{
_hours = hours;
}
public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
context.JobExpirationTimeout = TimeSpan.FromHours(_hours);
}
public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
context.JobExpirationTimeout = TimeSpan.FromHours(_hours);
}
}
你可以做类似的事情:
public class ExpirationAttribute : JobFilterAttribute, IElectStateFilter
{
private int _hours;
public ExpirationAttribute(int hours)
{
_hours = hours;
}
public void OnStateElection(ElectStateContext context)
{
var processing = context.CandidateState as ProcessingState;
if (processing == null)
{
return;
}
if (DateTime.UtcNow - context.BackgroundJob.CreatedAt > TimeSpan.FromHours(_hours))
{
context.CandidateState = new SucceededState(new { }, 0, 0) { Reason = "Execution skipped due to expiration." };
}
}
}
它只是将作业过期后移至成功,而不是处理它们。我根本没有测试过,但大体上应该是正确的。
另一个选项(或者可能作为故障保护机制)是在作业启动时检查作业的创建日期时间。缺点是作业将排队并标记为已完成。
public static void MyJob(PerformContext context)
{
if (DateTime.Now.Subtract(context.BackgroundJob.CreatedAt).TotalHours >= 1)
{
// Job is older than 1 hour
return;
}
// Process job...
}