# Cleaning up Job Table?

**URL:** <https://discuss.hangfire.io/t/cleaning-up-job-table/10065>\
**Category:** question\
**Tags:** sql-server\
**Created:** [July 4, 2023, 7:14am UTC](https://discuss.hangfire.io/t/cleaning-up-job-table/10065 "2023-07-04T07:14:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![SeeSharp](https://avatars.discourse-cdn.com/v4/letter/s/e9bcb4/32.png) [@SeeSharp](https://discuss.hangfire.io/u/SeeSharp)\
**Post date:** [July 4, 2023, 7:14am UTC](https://discuss.hangfire.io/t/cleaning-up-job-table/10065/1 "2023-07-04T07:14:39Z")

</div>

I wrote a script that cleans up the job table, but sadly it doesn’t clean it up - it fights with the running web-app for escalating locks - even running the script for 40mins doesn’t remove the records, even though SQL says it’s done and affected X rows.

The table has somewhere around 18.000 records, of which I’d like to delete everything older than 7 days.

DECLARE @DaysAgo DATETIME;  
DECLARE @RowsDeleted INT = 1, @counter INT = 1;  
SET @DaysAgo = DateAdd(DD,-7,GETDATE());

BEGIN TRANSACTION;

WHILE (@RowsDeleted \> 0)  
BEGIN  
DELETE top(10) FROM [HangFire].[Job] WHERE CreatedAt \< @DaysAgo;  
SELECT @RowsDeleted = @@ROWCOUNT, @counter += 1;  
IF @counter % 10 = 0  
BEGIN  
COMMIT TRANSACTION;  
BEGIN TRANSACTION;  
END  
END

COMMIT TRANSACTION;

Anyone knows of a solution that doesn’t involve shutting down hangfire?  
I’m considering to truncate the table, because we don’t really need the history - but it’d be a plus if we could keep records, younger than 7 days.

---

<div class="post-metadata">

**Author:** ![SeeSharp](https://avatars.discourse-cdn.com/v4/letter/s/e9bcb4/32.png) [@SeeSharp](https://discuss.hangfire.io/u/SeeSharp)\
**Post date:** [July 5, 2023, 6:39am UTC](https://discuss.hangfire.io/t/cleaning-up-job-table/10065/2 "2023-07-05T06:39:59Z")

</div>

was able to clean up the table, after removing the transaction,  
apparantly the table design is not optimal, 2 out of the 7 columns are of varchar(max), which causes a bloat in page size, each record uses a lot of storage, perhaps this could be changed / improved in the future.

cleaning up 22000 records, clears up almost 1.5gb of data, for smaller databases that run on lower specs this takes quite a while.

---

<div class="post-metadata">

**Author:** ![SeeSharp](https://avatars.discourse-cdn.com/v4/letter/s/e9bcb4/32.png) [@SeeSharp](https://discuss.hangfire.io/u/SeeSharp)\
**Post date:** [April 10, 2024, 8:11am UTC](https://discuss.hangfire.io/t/cleaning-up-job-table/10065/3 "2024-04-10T08:11:37Z")

</div>

Necro-ing this thread, is there any solution to this? Clearing up 22.000 records, to clean up 1.5gb of data is quite silly.

is there perhaps a way to automatically clean up the jobs that have expired after x amount of time?
