How do I run cron/scheduled task in Nextjs 9?

Issue

I’m building an app with Nextjs and I’m using pages/api directory for my api endpoints. The server entry/root is hidden for me. How do I immediately run the scheduled task with node-cron when my app is deployed then?

Solution

I had the same problem. What you can do are scheduled tasks with the node-cron library. You have to put your task which you want to schedule in your next.config.js file like so:

/** @type {import('next').NextConfig} */
const cron = require('node-cron');

cron.schedule('* * * * *', function () {
  console.log('Say scheduled hello')
});

const nextConfig = {
  reactStrictMode: true,
}

module.exports = nextConfig

Answered By – Gipfeli

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published