Created
February 5, 2023 12:24
-
-
Save Addono/d99884b20f935fc420ad39b528f93e5a to your computer and use it in GitHub Desktop.
Global static singleton jobs in Nest.js with Bull
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
import { Injectable, OnModuleInit } from "@nestjs/common"; | |
const QUEUE_NAME = "my-job-queue"; | |
const STATIC_CRON_JOB_NAME = "static-schedule"; | |
export interface MyQueueJob {} | |
@Injectable() | |
export class MyQueueService implements OnModuleInit { | |
constructor( | |
@InjectQueue(QUEUE_NAME) | |
private myQueue: Queue<MyQueueJob> | |
) {} | |
async onModuleInit() { | |
await scheduleCronnedSingletonJob({ | |
cron: "* * * * *", // Run every minute | |
jobName: STATIC_CRON_JOB_NAME, | |
queue: this.myQueue, | |
}); | |
} | |
} | |
@Processor(QUEUE_NAME) | |
export class MyQueueProcessor { | |
@Process(STATIC_CRON_JOB_NAME) | |
async processStaticJob(job: Job<MyQueueJob>) { | |
console.log(`Process job`); // Process job | |
} | |
} |
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
import { Queue } from "bull"; | |
export const scheduleCronnedSingletonJob = async (params: { | |
queue: Queue; | |
jobName: string; | |
cron: string; | |
}): Promise<void> => { | |
// Remove all old instances | |
const repeatableJobs = await params.queue.getRepeatableJobs(); | |
for (const job of repeatableJobs) { | |
if (job.name === params.jobName) { | |
await params.queue.removeRepeatableByKey(job.key); | |
} | |
} | |
// Schedule a new instance | |
await params.queue.add( | |
params.jobName, | |
{}, | |
{ | |
repeat: { | |
cron: params.cron, | |
}, | |
} | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment