ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. node-cron to schedule tasks

node-cron to schedule tasks

Here’s a step-by-step tutorial on how to set up a new Node.js project using node-cron to schedule tasks. This tutorial will guide you through creating a structured project where cron jobs are placed in a separate file and automatically executed at intervals.

Step 1: Install Node.js and npm

Make sure you have Node.js and npm installed on your machine. You can check by running the following commands:

node -v
npm -v

If they are not installed, download Node.js from here.

Step 2: Create a New Node.js Project

  1. Create a new directory for your project and navigate into it:
mkdir node-cron-example
cd node-cron-example

Initialize a new Node.js project with npm:

npm init -y

This will create a package.json file to manage dependencies and project settings.

Step 3: Install node-cron

Now, you need to install the node-cron package, which will help us schedule tasks.

npm install node-cron

Step 4: Project Structure

To keep your project structured and maintainable, create the following structure:

node-cron-example/

├── cron-jobs/
   └── cleanupJob.js       # File that contains the cron job

├── app.js                  # Main application file
├── package.json

Step 5: Set Up a Cron Job

  1. Create the cron-jobs/cleanupJob.js file:
mkdir cron-jobs
touch cron-jobs/cleanupJob.js

In cron-jobs/cleanupJob.js, we will define a simple task that prints a message to the console every minute.

cron-jobs/cleanupJob.js

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

// Function that runs the cron job
const cleanupJob = () => {
    // Schedule the task to run every minute
    cron.schedule('* * * * *', () => {
        console.log('Running the cleanup job every minute');
    });
};

module.exports = cleanupJob;

Step 6: Setup the Main Application File

  1. Create the app.js file:
touch app.js
  1. In app.js, we will import the cron job and start the application.
  2. app.js
const cleanupJob = require('./cron-jobs/cleanupJob');

// Call the cleanup job to schedule it
cleanupJob();

console.log('Cron job application has started.');

Step 7: Run the Application

Now, let’s run the application and see the cron job in action.

  1. Run your application:
node app.js

You should see the message Cron job application has started. in the console, followed by the message Running the cleanup job every minute every minute.

Step 8: Customizing the Cron Job Schedule

The cron job schedule is defined using cron syntax in this line:

cron.schedule('* * * * *', () => {

Here’s a quick explanation of the syntax:

*    *    *    *    *
|    |    |    |    |
|    |    |    |    └─── Day of the week (0 - 7) (0 or 7 is Sunday)
|    |    |    └───────── Month (1 - 12)
|    |    └────────────── Day of the month (1 - 31)
|    └─────────────────── Hour (0 - 23)
└──────────────────────── Minute (0 - 59)

For example:

  • * * * * *: Every minute
  • 0 * * * *: Every hour
  • 0 0 * * *: Every day at midnight

You can adjust the schedule based on your requirements.

Step 9: Example: Run Every 5 Minutes

If you want to run the job every 5 minutes, modify the cron schedule like this:

cron-jobs/cleanupJob.js

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

// Function that runs the cron job
const cleanupJob = () => {
    // Schedule the task to run every 5 minutes
    cron.schedule('*/5 * * * *', () => {
        console.log('Running the cleanup job every 5 minutes');
    });
};

module.exports = cleanupJob;

Step 10: Automating Tasks in Production

When deploying this to production, ensure that your Node.js application runs continuously using tools like PM2, which is a process manager for Node.js. PM2 will keep your app running and restart it if it crashes.

  1. Install PM2 globally:
npm install pm2 -g
  1. Start your app with PM2:
pm2 start app.js

This will keep your application and cron jobs running even after you close the terminal.

Conclusion

You have now created a simple Node.js project with node-cron that runs a task at regular intervals. Here’s a summary of the steps:

  1. Created a Node.js project.
  2. Installed node-cron to handle scheduled tasks.
  3. Structured the project by storing cron jobs in a separate directory.
  4. Created a simple cron job that runs every minute or at any interval you define.

Now, your cron jobs will run automatically without needing any manual intervention!

How can we help?