Hangfire Failed Job Cleanup - SQL Server Storage

Tags: #<Tag:0x00007fafef3aede0> #<Tag:0x00007fafef3aecf0>

Can someone please tell me how to configure the Failed SQL Server job cleanup? I’d like to only keep 3 days of hangfire jobs to minimize the database storage.

I created a Trigger on Hangfire.Job table in SQL Server Insert/update, seems to be working:

/****** Object: Trigger [HangFire].[SetExpirationToHangfireFailedJobs] Script Date: 12/29/2021 11:59:20 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [HangFire].[SetExpirationToHangfireFailedJobs]
ON [HangFire].[Job]
AFTER INSERT, UPDATE
AS
BEGIN
	DECLARE
	@Id bigint,
	@StateName nvarchar(20),
	@ExpireAt datetime,
	@NumDaysExpire int = 7

	SET NOCOUNT ON;

	SELECT @Id= INSERTED.Id,
	@StateName = INSERTED.[StateName],
	@ExpireAt= INSERTED.[ExpireAt] FROM INSERTED
	IF (@StateName = 'Failed' AND @ExpireAt IS NULL)
	BEGIN
		UPDATE Hangfire.Job
		SET
			HangFire.Job.ExpireAt = DATEADD(day, @NumDaysExpire, getdate())
		WHERE 
			Hangfire.Job.ExpireAt IS NULL
			AND Hangfire.Job.Id = @Id
	END
END