node.jsnode-cron

How to write cronjobs in seperate file nodejs


I want to write a cron job on node.js which runs every minute. The tutorials that I viewed online all showed the cron job being written in the "App.js" or "server.js" file which is the main file on nodejs.

I want to seperate this into another file for better readability but I cannot find any solution or example online. please help.

I want to write this in a separate file just like we write our routes.

const cron = require("node-cron");

cron.schedule("* * * * *", function() {
    console.log("running a task every minute");
});

Solution

  • yes. you can write your cron-job in separte file. when starting the server, you can invoke your cron job, like in your app.js or server.js. you just export your cron job file & impore here

    import cronJob from "../filename.js"        
    server.listen(3000, () => {
       cronJob.start();
    });