How to Setup Scheduled Functions with NodeJs, Express and Node-Cron

September 21, 2021

  1. Create a NodeJs application

    - npm init

    - npm i express

  2. Setup the express server

    - Create the app.js file (or server.js is you prefer)

const express = require("express");
const app = express();
app.set("port", process.env.PORT || 3000);

app.listen(app.get("port"), () => {
  console.log("Express server listening on port " + app.get("port"));
});
  1. Add node-cron npm package to the application

    - npm i node-cron

  2. Set up a scheduled jobs folder & files

    - Create a folder called “scheduled jobs”

  3. Create the logic of the scheduled jobs

    - In the above folder, either create a single file to hold all your scheduled function logic or if preferred, a file per scheduled logic

    - The scheduled logic needs to be configured as so:

    const CronJob = require("node-cron");
    
    exports.initScheduledJobs = () => {
      const scheduledJobFunction = CronJob.schedule("*/5 * * * *", () => {
        console.log("I'm executed on a schedule!");
      });
    
      scheduledJobFunction.start();
    }

    - The frequency at which this logic is executed is defined by the Cron Schedule Expression defined as the first argument to the Cron.schedule function.

    A really good resource to play around with schedule expressions is the Crontab Guru. Experimenting with the schedules will allow you to find what schedule expression you require.

  4. Configure the express app to initialise the job schedules

    - In the app.js file add a call to the init function(s) from your scheduled file(s).

    const express = require("express");
    const scheduledFunctions = require('./scheduledFunctions');
    const app = express();
    app.set("port", process.env.PORT || 3000);
    
    // ADD CALL HERE
    scheduledFunctions.initScheduledJobs();
    
    app.listen(app.get("port"), () => {
      console.log("Express server listening on port " + app.get("port"));
    });

    This will generate the functions and their schedules in the Cron scheduler when your app starts up.