原文:https://github.com/HangfireIO/Hangfire/issues/620
/// <summary>
/// 错过不执行
/// </summary>
public class NoMissedRunsAttribute : JobFilterAttribute, IClientFilter
{
/// <summary>
/// 设置逾期时间
/// </summary>
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromMinutes(15);
public void OnCreating(CreatingContext context)
{
if (context.Parameters.TryGetValue("RecurringJobId", out var recurringJobId) &&
context.InitialState?.Reason == "Triggered by recurring job scheduler")
{
// the job being created looks like a recurring job instance,
// and triggered by a scheduler (i.e. not manually) at that.
var recurringJob = context.Connection.GetAllEntriesFromHash($"recurring-job:{recurringJobId}");
if (recurringJob != null && recurringJob.TryGetValue("NextExecution", out var nextExecution))
{
// the next execution time of a recurring job is updated AFTER the job instance creation,
// so at the moment it still contains the scheduled execution time from the previous run.
var scheduledTime = JobHelper.DeserializeDateTime(nextExecution);
if (DateTime.UtcNow > scheduledTime + MaxDelay)
{
// the job is created way later than expected
context.Canceled = true;
}
}
}
}
public void OnCreated(CreatedContext context)
{
}
}使用方式:
在执行的job上
/// <summary>
/// 执行同步操作
/// </summary>
//[UnitOfWork]
[NoMissedRunsAttribute]
public virtual async Task Execute()
{
.....
}