Skip to content

Instantly share code, notes, and snippets.

@tyteen4a03
Created November 1, 2024 17:11
Show Gist options
  • Save tyteen4a03/e0f3c385ea780354c08d3debad71f033 to your computer and use it in GitHub Desktop.
Save tyteen4a03/e0f3c385ea780354c08d3debad71f033 to your computer and use it in GitHub Desktop.
Payload 3.0 Cron Runner
import { createServer } from "node:http";
import { parse } from "node:url";
import { initGraphClient } from "@/modules/msgraph/client";
import { rosterfyImportWorkflowId } from "@/modules/volunteer/workflows/rosterfyImportWorkflow";
import config from "@payload-config";
import next from "next";
import cron from "node-cron";
import { getPayload } from "payload";
const port = Number.parseInt(process.env.PORT || "3010");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const ALLOWLISTED_ROUTES = ["/health"];
const start = async () => {
initGraphClient();
await app.prepare();
createServer((req, res) => {
const parsedUrl = parse(req.url ?? "", true);
if (!ALLOWLISTED_ROUTES.includes(parsedUrl.pathname ?? "/")) {
res.statusCode = 404;
res.end("not found");
}
void handle(req, res, parsedUrl);
}).listen(port);
console.log(`> Server listening at http://localhost:${port} as ${dev ? "development" : process.env.NODE_ENV}`);
const payload = await getPayload({ config });
let currentlyRunning = false;
cron.schedule("*/5 * * * *", async () => {
if (currentlyRunning) {
return;
}
currentlyRunning = true;
const start = new Date();
console.log(`Starting Rosterfy import cron at ${start}...`);
try {
await payload.jobs.queue({
workflow: rosterfyImportWorkflowId,
input: {
now: start,
},
});
await payload.jobs.run();
} catch (e) {
console.error("Could not execute Rosterfy import cron");
console.error(e);
}
currentlyRunning = false;
});
};
void start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment