Hangfire implements expired job settings to prevent unlimited data growth

Time:2021-7-17

background

The background job hangfire is used to perform some tasks in the application in the background. The background job is persistent, which means that even if your application crashes, the background job will be retried and executed later. We usually persist data to storage media, such as redis. This will bring a problem, how to prevent the unlimited expansion of data, we can set the expired job to prevent the unlimited growth of data.

resolvent

1. Define succeededstateexpirehandler and inherit istatehandler.

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

namespace CompanyName.ProjectName.Hangfire.Job.Code
{
    /// 
    ///The completed job settings are out of date to prevent unlimited data growth
    /// 
    public class SucceededStateExpireHandler : IStateHandler
    {
        public TimeSpan JobExpirationTimeout;

        public SucceededStateExpireHandler(int jobExpirationTimeout)
        {
            JobExpirationTimeout = TimeSpan.FromMinutes(jobExpirationTimeout);
        }

        public string StateName => SucceededState.StateName;

        public void Apply(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            context.JobExpirationTimeout = JobExpirationTimeout;
        }

        public void Unapply(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
        }
    }
}

2. Set the expiration time.

    JobExpirationTimeout = TimeSpan.FromMinutes(jobExpirationTimeout);

3. Add and enable in configureservices.

public IServiceProvider ConfigureServices(IServiceCollection services)
{
..........................
GlobalStateHandlers.Handlers.Add(new SucceededStateExpireHandler(int.Parse(Configuration["Hangfire:JobExpirationTimeout"])));
}

summary

1. It is necessary to set the expiration date of data, especially in the case of large amount of data, which can effectively save resources and improve the speed.

2. For the duration of validity, it depends on their business needs.