import { Cron } from "croner"; import { createLogger } from "../logger/logger.controller.js"; // example createJob // createCronJob("test Cron", "*/5 * * * * *", async () => { // console.log("help"); // }); export interface JobInfo { name: string; schedule: string; nextRun: Date | null; isRunning: boolean; } // Store running cronjobs export const runningCrons: Record = {}; export const createCronJob = async ( name: string, schedule: string, // cron string with 8 8 IE: */5 * * * * * every 5th second task?: () => Promise, // what function are we passing over ) => { // get the timezone based on the os timezone set const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; // Destroy existing job if it exists if (runningCrons[name]) { runningCrons[name].stop(); } // Create new job with Croner runningCrons[name] = new Cron( schedule, { timezone: timeZone, catch: true, // Prevents unhandled rejections name: name, }, task, ); const log = createLogger({ module: "system", subModule: "croner" }); log.info({}, `A job for ${name} was just created.`); }; export const getAllJobs = (): JobInfo[] => { return Object.entries(runningCrons).map(([name, job]) => ({ name, schedule: job.getPattern() || "invalid", nextRun: job.nextRun() || null, lastRun: job.previousRun() || null, isRunning: job.isRunning(), //job ? !job.isStopped() : false, })); }; export const removeCronJob = (name: string) => { if (runningCrons[name]) { runningCrons[name].stop(); delete runningCrons[name]; } }; export const stopCronJob = (name: string) => { if (runningCrons[name]) { runningCrons[name].pause(); } }; export const resumeCronJob = (name: string) => { if (runningCrons[name]) { runningCrons[name].resume(); } };