Next.js Discord

Discord Forum

CronJob not working

Unanswered
Backxtar posted this in #help-forum
Open in Discord
I have this ./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

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
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
is there no solution to run functions with cron libary?
without a custom next server? no
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
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
ye
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
is there no option in nextjs to start a job on server start?
With a custom next server, yes
without, no
i mean yes i can write a seperate js file to loop but ye thats stupid
the cache is a seperate db
nextjs runs functions on request time
redis db
i host all my websites not on vercel
i host it in docker
nice
u have so many options for setting up cronjobs
but nextjs isnt for that
ye but oh man 😦 so i need a different service to update redis db
yup
crazy