Job scheduler — runs tasks at specific times or intervals.
1const cron = require("node-cron");23// Run every day at midnight4cron.schedule("0 0 * * *", async () => {5 console.log("Running daily cleanup...");6 await cleanupExpiredSessions();7 await generateDailyReport();8});910// Run every 5 minutes11cron.schedule("*/5 * * * *", async () => {12 await syncExternalData();13});1415// With error handling16cron.schedule("0 * * * *", async () => {17 try {18 await processQueue();19 } catch (err) {20 console.error("Job failed:", err);21 await notifyAdmin(err);22 }23});
Using BullMQ (distributed):
1const { Queue, Worker } = require("bullmq");23const cleanupQueue = new Queue("cleanup");45// Add delayed job6await cleanupQueue.add("daily-cleanup", {}, {7 repeat: { cron: "0 0 * * *" },8});910const worker = new Worker("cleanup", async (job) => {11 await cleanupExpiredSessions();12});
Key points: