-
Notifications
You must be signed in to change notification settings - Fork 469
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add job to delete old AgendaJobs (#2646)
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import Agenda from "agenda"; | ||
import { trackJob } from "../services/otel"; | ||
import { getAgendaInstance } from "../services/queueing"; | ||
import { logger } from "../util/logger"; | ||
const JOB_NAME = "deleteOldAgendaJobs"; | ||
|
||
// Delete old agenda jobs that finished over one week ago and are not going to be repeated | ||
const deleteOldAgendaJobs = trackJob(JOB_NAME, async () => { | ||
const agenda = getAgendaInstance(); | ||
|
||
const startDate = Date.now(); | ||
|
||
const res = await agenda._collection | ||
.find( | ||
{ | ||
lastFinishedAt: { $lt: new Date(Date.now() - 7 * 24 * 3600 * 1000) }, | ||
nextRunAt: null, | ||
}, | ||
{ | ||
limit: 1000, | ||
projection: { _id: 1 }, | ||
} | ||
) | ||
.toArray(); | ||
|
||
const ids = res.map((r) => r._id); | ||
|
||
const deleteRes = await agenda._collection.deleteMany({ _id: { $in: ids } }); | ||
|
||
logger.info( | ||
`Deleted ${deleteRes.deletedCount} old agenda jobs in ` + | ||
(Date.now() - startDate) + | ||
`ms` | ||
); | ||
}); | ||
|
||
export default async function (agenda: Agenda) { | ||
agenda.define(JOB_NAME, deleteOldAgendaJobs); | ||
|
||
const job = agenda.create(JOB_NAME, {}); | ||
job.unique({}); | ||
job.repeatEvery("5 minutes"); | ||
await job.save(); | ||
} |