How to run Cron jobs in Node.js?

Better Stack Team
Updated on October 5, 2023

To run Cron jobs in Node.js, you can use a Node.js package called node-cron. Here are the steps to create and schedule a Node.js script using node-cron:

Install node-cron

You can install node-cron using the Node Package Manager (npm) with the following command:

 
npm install node-cron

🔭 Want to get alerted when your Cron doesn’t run correctly?

Go to Better Stack and start monitoring in 5 minutes.

Create a Node.js script

Create a Node.js script with the code you want to run as a Cron job. For example, let's say you want to delete all temporary files from a directory every day at midnight. You can create a Node.js script called cleanup.js with the following code:

 
const fs = require('fs');
const path = require('path');
const cron = require('node-cron');

// Set the directory to clean up
const dirPath = '/path/to/temp/files/';

// Define the Cron job schedule
cron.schedule('0 0 * * *', () => {
  // Get a list of all files in the directory
  fs.readdir(dirPath, (err, files) => {
    if (err) throw err;

    // Delete all files in the directory
    for (const file of files) {
      fs.unlink(path.join(dirPath, file), (err) => {
        if (err) throw err;
      });
    }
  });
});

This code uses node-cron to define a Cron job that runs every day at midnight. The code inside the Cron job deletes all files in the directory specified by dirPath.

Schedule the Cron job

You can schedule the Cron job by running the Node.js script using the following command:

 
node /path/to/cleanup.js

This will start the Cron job and run the code defined in the cleanup.js script. The Cron job will continue to run until you stop the Node.js process.

Verify the Cron job

You can verify that the Cron job is running by checking the output of the Node.js process. You should see output from the console.log() statements in the script every time the Cron job runs.

By following these steps, you can create and schedule a Node.js script to run as a Cron job using node-cron.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github