CronJob not working
Unanswered
Backxtar posted this in #help-forum
BackxtarOP
I have this
Now i want to run the cron job in the background of the app / when server starts.
but they dont find the file ... i cant get this cronjob to work...
./lib/cron.ts file:import axios from "axios";
import cron from "node-cron";
import redis from "./redis";
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
};
async function updateCache(): Promise<void> {
try {
const { data } = await axios.get(
"url"
);
await redis.set("news-data", data);
console.log(`Cache: News succesfully updated`);
} catch (error) {
console.log("Cache: Error while updating news");
}
}
export const startCronJob = () => {
updateCache(); // Initial cache update
cron.schedule("* * * * *", async () => {
const now = new Date();
const time = now.toLocaleString("de-DE", options).replace(/\./g, "-");
console.log(`Cron-Job running at ${time}: Cache`);
await updateCache();
});
};Now i want to run the cron job in the background of the app / when server starts.
next.config.mjs/** @type {import('next').NextConfig} */
const nextConfig = {};
import { startCronJob } from "./lib/cron.js";
startCronJob();
export default nextConfig;but they dont find the file ... i cant get this cronjob to work...
35 Replies
BackxtarOP
cant get this to work -.-
@Backxtar cant get this to work -.-
Hey, the next config is not intended for that
either u do it via a custom next server, or in your edge environment
BackxtarOP
what do u mean with edge env
vercel for example
if u host your nextjs app on vercel u can have cronjobs that can fetch your next endpoint
BackxtarOP
is there no solution to run functions with cron libary?
without a custom next server? no
BackxtarOP
the problem is i can call the start cron job on the layout.tsx
but it calls more than 1 time
layout.tsx and any other rsc component runs on request
it doesnt run traditionally like a node app
BackxtarOP
like:
startCronJob();
export default function RootLayout({ children }: RootProps) {
return (
<html lang="en">
<body
className={`${bodyFont.variable} ${headerFont.variable} flex flex-col min-h-screen`}
>
<Header />
<main className="flex-grow container pt-6 pb-6 shadow-md">
{children}
</main>
<Footer />
</body>
</html>
);
}its serverless
BackxtarOP
ye
BackxtarOP
i know its called multiple times
it will still not work even if u handle it in a singleton
u need a server for that
BackxtarOP
is there no option in nextjs to start a job on server start?
With a custom next server, yes
without, no
BackxtarOP
i mean yes i can write a seperate js file to loop but ye thats stupid
@Backxtar i mean yes i can write a seperate js file to loop but ye thats stupid
that will still not work
BackxtarOP
the cache is a seperate db
nextjs runs functions on request time
BackxtarOP
ye but oh man 😦 so i need a different service to update redis db
yup
BackxtarOP
crazy