Task scheduler — run tasks on a schedule.
1const schedule = require("node-schedule");23// Run every day at 9 AM4schedule.scheduleJob("0 9 * * *", async () => {5 console.log("Running daily report...");6 await generateDailyReport();7});89// Run every 5 minutes10schedule.scheduleJob("*/5 * * * *", async () => {11 await syncData();12});1314// Custom scheduler with persistence15class TaskScheduler {16 constructor(db) {17 this.db = db;18 this.jobs = new Map();19 }2021 async schedule(name, cronExpression, handler) {22 const job = schedule.scheduleJob(cronExpression, async () => {23 try {24 await handler();25 await this.db.saveRun(name, "success");26 } catch (err) {27 await this.db.saveRun(name, "failed", err.message);28 }29 });3031 this.jobs.set(name, job);32 await this.db.saveSchedule(name, cronExpression);33 }3435 cancel(name) {36 const job = this.jobs.get(name);37 if (job) job.cancel();38 this.jobs.delete(name);39 }4041 async restoreAll() {42 const schedules = await this.db.getAllSchedules();43 for (const s of schedules) {44 await this.schedule(s.name, s.cron, s.handler);45 }46 }47}