How to configure the retention time of job?

First of all, retention, or expiration time is setting up only for successful and deleted jobs. Other job states, including the failed state, don’t have any expiration time. That is why your failed jobs will be kept infinitely before you fix/retry or delete them manually.

But if you really want to set up retention time for succeeded or deleted jobs, you can add the following job filter (they are like action filters in ASP.NET MVC):

public class ProlongExpirationTimeAttribute : JobFilterAttribute, IApplyStateFilter
{
    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        context.JobExpirationTimeout = TimeSpan.FromDays(7);
    }
}

And apply this filter globally…

GlobalJobFilters.Filters.Add(new ProlongExpirationTimeAttribute());

… or locally, by decorating the method or its class:

[ProlongExpirationTime]
public void SomeMethod()
{
    // Implementation
}

In the recent versions of Hangfire it is also possible to specify the expiration globally by using the WithJobExpirationTimeout method just after the UseXXXStorage (where XXX is the storage you are using) and pass the required timeout as an argument.

Configuration
    .UseXXXStorage()
    .WithJobExpirationTimeout(TimeSpan.FromDays(4))
9 Likes