如果逾期,则Hang​​fire配置延迟的任务到期时间

时间:2018-04-16 09:27:15

标签: hangfire delayed-execution

是否可以设置延迟任务的配置到期时间? 如果它们已经过期,如果配置的时间已经过去,请将它们丢弃?

1 个答案:

答案 0 :(得分:0)

我不知道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());
}

注意:代码未经过测试,这是一般的想法