Search code examples
c#hangfire

Set Hangfire succeeded job expiry attribute not working


I am using Hangfire to do jobs, and I'd like to change the behaviour that succeeded jobs are deleted from the database after a day - I'd like them to be stored for a year.

Following the instructions in this thread, which is the same as in this SO question, I have created a class:

public class OneYearExpirationTimeAttribute : JobFilterAttribute, IApplyStateFilter
{
    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        context.JobExpirationTimeout = TimeSpan.FromDays(365);
    }

    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        context.JobExpirationTimeout = TimeSpan.FromDays(365);
    }
}

and I register it in my Asp.net web api startup class as a global filter:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // ... other stuff here ...
        GlobalJobFilters.Filters.Add(new OneYearExpirationTimeAttribute());
        GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDBConnection");
        app.UseHangfireDashboard();
    }
}

The web api is the place where jobs are posted (i.e., the call to BackgroundJob.Enqueue(() => ...) happens). I have not changed the configuration of the clients that do the actual jobs.

If I now post a job and it succeeds, it still has a expiry of one day as you can see in the screenshot, which shows both the dashboard and the entry in the HangfireDb,

enter image description here

What am I doing wrong or what am I missing?


Solution

  • My mistake in setup was that the attribute was set on the wrong application. As I stated in the question, I added the filter in the startup.cs file of the asp.net web api where jobs are posted.

    Instead I should have added the configuration in the Console application where the jobs are being executed, i.e., my console app starts with

    static void Main(string[] args)
    {
        GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDBConnection");
        GlobalJobFilters.Filters.Add(new OneYearExpirationTimeAttribute());
        // ... more stuff ...
    }
    

    Then it works. The Hangfire documentation could be a bit clearer on where the filter should be configured.