Simple Node-Cron Example in Node.js

Scheduling tasks is often an important part of our applications. In this article, we will explore how to schedule tasks in a Node.js application using the node-cron library.

Node-Cron is a task scheduler for Node.js, based on the popular cron syntax used in Unix-like systems. It allows you to schedule tasks at specific intervals, such as every minute, hour, day, or week.

You need to install the node-cron package:

npm install node-cron

Now we can jump into how to use it:

How to

Let's create a simple example to help you understand how node-cron works. We'll schedule a task to run every minute and print a message to the console:

// index.js
const cron = require('node-cron');

// Schedule a task to run every minute
cron.schedule('* * * * *', () => {
  console.log('Task is running every minute');
});

console.log('Node-Cron job scheduled');

The cron syntax '* * * * *' means "every minute of every hour of every day of every month and every day of the week."

Let's break down the syntax if it's new to you:

Cron Syntax

The cron syntax consists of five fields separated by spaces:

Showing what each of the "*" mean in Cron syntax

You can customize the schedule by changing these fields.

Here are some examples:

  • 0 * * * * - Runs at the start of every hour.
  • 0 0 * * * - Runs at midnight every day.
  • 0 0 1 * * - Runs at midnight on the first day of every month.
  • 0 0 * * 0 - Runs at midnight every Sunday.

I use crontab guru to remind me of the syntax because I never remember the syntax.

Nodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.