Keep history of jobs executed for more than 1 day in Hangfire
Asked Answered
N

2

12

I've just started using Hangfire, and I am loving it.

I understand that Hangfire maintains the history for succeeded jobs for 1 day, and clear it thereafter.

Is there is a way where I can customize this default behavior and persist the history for any duration say 7 days?

Nigrescent answered 24/12, 2015 at 10:0 Comment(0)
N
15

To do this, you need to create a job filter and register it through hangfire global configurations, as discussed here - https://discuss.hangfire.io/t/how-to-configure-the-retention-time-of-job/34

Create job filter -

using Hangfire.Common;
using Hangfire.States;
using Hangfire.Storage;
using System;

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

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

...and register in global job filters -

GlobalJobFilters.Filters.Add(new ProlongExpirationTimeAttribute());
Nigrescent answered 5/1, 2016 at 9:17 Comment(0)
Q
6

Copy from link https://discuss.hangfire.io/t/how-to-configure-the-retention-time-of-job/34 from Yogy:

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))
Qumran answered 27/10, 2023 at 11:42 Comment(1)
Perfect, this worked for me. Here is a separate source as well - docs.hangfire.io/en/latest/background-methods/index.htmlCollbaith

© 2022 - 2024 — McMap. All rights reserved.