0
0
NodejsHow-ToBeginner · 3 min read

How to Use Cron Job in Node.js: Simple Guide with Examples

In Node.js, you can use the node-cron package to schedule cron jobs that run tasks at specific times or intervals. Install it with npm install node-cron, then create a cron job using cron.schedule() with a cron expression and a callback function to run your code on schedule.
📐

Syntax

The basic syntax to create a cron job in Node.js using node-cron is:

  • cron.schedule(cronExpression, callbackFunction): schedules the task.
  • cronExpression: a string defining when the task runs (like '*/5 * * * *' for every 5 minutes).
  • callbackFunction: the function to run at the scheduled time.
javascript
import cron from 'node-cron';

cron.schedule('cronExpression', () => {
  // task code here
});
💻

Example

This example schedules a task to run every minute and logs a message to the console.

javascript
import cron from 'node-cron';

cron.schedule('* * * * *', () => {
  console.log('Running a task every minute');
});
Output
Running a task every minute
⚠️

Common Pitfalls

Common mistakes when using cron jobs in Node.js include:

  • Using incorrect cron expressions that do not match the intended schedule.
  • Not keeping the Node.js process running, so the cron job never triggers.
  • Forgetting to import or install node-cron.
  • Running blocking or long tasks inside the cron callback, which can delay other scheduled jobs.
javascript
import cron from 'node-cron';

/* Wrong cron expression example (runs once a month instead of every minute) */
cron.schedule('0 0 1 * *', () => {
  console.log('Runs only on the first day of each month');
});

/* Correct cron expression for every minute */
cron.schedule('* * * * *', () => {
  console.log('Runs every minute');
});
📊

Quick Reference

Here is a quick guide to common cron expression parts:

FieldAllowed ValuesDescription
Minute0-59Minute of the hour
Hour0-23Hour of the day
Day of Month1-31Day of the month
Month1-12Month of the year
Day of Week0-7Day of the week (0 or 7 is Sunday)

Key Takeaways

Use the node-cron package to schedule cron jobs easily in Node.js.
Cron expressions define when your task runs; learn their format carefully.
Keep your Node.js process running to allow cron jobs to execute.
Avoid blocking code inside cron callbacks to keep schedules accurate.
Test cron expressions with simple tasks before using complex logic.