Search code examples
hangfirehangfire-autofac

How do I make Hangfire pick jobs queued in the last hour?


My requirement is to process only latest jobs and ignore older jobs. How do I configure that in Hangfire?

I have tried IApplyStateFilter for setting 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);
    }
}

Solution

  • Another option (or maybe as a failsafe mechanism) is to check the creation DateTime of the job when it is started. The downside is that the Job will be queued and marked as completed.

    public static void MyJob(PerformContext context)
    {
        if (DateTime.Now.Subtract(context.BackgroundJob.CreatedAt).TotalHours >= 1)
        {
            // Job is older than 1 hour
            return;
        }
    
        // Process job...
    }