Author: Arunangshu Das
Url: https://article.arunangshudas.com/7-steps-to-automate-node-js-tasks-with-cron-jobs-0dfb1a8cbeba
Date Published: March 30, 2025
Content: 7 Steps to Automate Node.js Tasks with Cron Jobs
--
Automation is the secret sauce behind smooth-running applications, efficient workflows, and reduced manual effort. If you’re working with Node.js, chances are you need to run tasks at scheduled intervals — be it sending emails, cleaning up databases, or fetching external data. That’s where cron jobs come in.
What Are Cron Jobs?
Cron jobs are scheduled tasks that run at predefined times or intervals. The system’s cron daemon (scheduler) executes these tasks without requiring manual intervention. Cron jobs are common in UNIX-like operating systems (Linux, macOS) but can also be used on Windows with alternative tools.
For example, you can schedule a cron job to:
- Run a script every morning at 8 AM
- Send reports at the end of every month
- Check for inactive users and remove them daily at midnight
In Node.js, we use packages like node-cron or agenda to create and manage cron jobs efficiently.
Step 1: Install Node.js and Required Packages
Before we start, make sure you have Node.js installed on your machine. If you don’t, download and install it from nodejs.org.
Once Node.js is set up, create a new project folder and initialize it:
mkdir cron-job-democd cron-job-demonpm init -y
Now, install the node-cron package, which allows us to schedule tasks in Node.js:
npm install node-cron
You can also use agenda (MongoDB-backed job scheduling) or bull (Redis-backed queue management), but for this guide, we’ll stick with node-cron as it’s simple and lightweight.
Step 2: Understanding Cron Job Syntax
Cron jobs use a five-field syntax to define schedules:
* * * * * command_to_execute| | | | || | | | +----- Day of the Week (0 - 7) (Sunday = 0 or 7)| | | +------- Month (1 - 12)| | +--------- Day of the Month (1 - 31)| +----------- Hour (0 - 23)+------------- Minute (0 - 59)
Here are some examples:
- 0 9 * * * → Runs every day at 9:00 AM
- */10 * * * * → Runs every 10 minutes
- 0 0 * * 0 → Runs every Sunday at midnight
- 15 14 1 * * → Runs at 2:15 PM on the 1st day of every month
The * means every possible value for that field (e.g., every minute, every hour, etc.).
Step 3: Create a Simple Cron Job in Node.js
Let’s create a basic cron job that logs a message every minute.
Create index.js
const cron = require('node-cron');console.log('Scheduler is running...');cron.schedule('* * * * *', () => { console.log(`Job executed at ${new Date().toLocaleTimeString()}`);});
Run the Script
Save the file and start your cron job with:
node index.js
You’ll see the message “Job executed at [time]” appear in the console every minute.
Step 4: Automate a Real-World Task
Let’s say we want to send a daily email report at 8 AM.
1) Install Nodemailer for Emails
npm install nodemailer
2) Update index.js
const cron = require('node-cron');const nodemailer = require('nodemailer');const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'your-email@gmail.com', pass: 'your-password', },});const sendReportEmail = async () => { try { await transporter.sendMail({ from: '"Daily Report" <your-email@gmail.com>', to: 'recipient@example.com', subject: 'Your Daily Report', text: 'This is an automated daily report!', }); console.log('Email sent successfully'); } catch (error) { console.error('Error sending email:', error); }};// Schedule the email job at 8 AM dailycron.schedule('0 8 * * *', () => { console.log('Running email job...'); sendReportEmail();});console.log('Email scheduler running...');
3) Run the Script
node index.js
This cron job will send an email every day at 8 AM.
Step 5: Handling Errors and Logging
Cron jobs should log errors and results to avoid silent failures.
Modify the sendReportEmail function
const fs = require('fs');const sendReportEmail = async () => { try { await transporter.sendMail({ from: '"Daily Report" <your-email@gmail.com>', to: 'recipient@example.com', subject: 'Your Daily Report', text: 'This is an automated daily report!', }); fs.appendFileSync('cron.log', `[${new Date()}] Email sent successfully\n`); } catch (error) { fs.appendFileSync('cron.log', `[${new Date()}] Error: ${error.message}\n`); }};
Now, all logs are saved in cron.log.
Step 6: Running Cron Jobs in the Background
Instead of keeping your terminal open, you can run the script in the background using PM2.
1) Install PM2 globally:
npm install -g pm2
2) Start the script:
pm2 start index.js --name "cron-job"
3) Check logs anytime:
pm2 logs cron-job
4) Stop the cron job:
pm2 stop cron-job
Now, even if you close the terminal, your job keeps running!
Step 7: Deploying Cron Jobs to a Server
If you’re using a Linux server, you can schedule your script to run automatically by adding it to crontab:
crontab -e
Add this line at the bottom:
@reboot /usr/bin/node /path/to/index.js
This ensures your cron job starts every time the server reboots.
Wrapping Up
By following these seven steps, you’ve automated Node.js tasks using cron jobs!
Quick Recap:
→ Installed node-cron and understood cron syntax → Created a simple cron job → Automated a real-world task (sending emails) → Handled errors and logs → Ran cron jobs in the background → Set up cron jobs on a server
Now, you can use cron jobs for:
- Automated backups
- Database cleanups
- API data fetching
- Sending scheduled notifications
You may also like:
- 10 Common Mistakes with Synchronous Code in Node.js
- Why 85% of Developers Use Express.js Wrongly
- Implementing Zero-Downtime Deployments in Node.js
- 10 Common Memory Management Mistakes in Node.js
- 5 Key Differences Between ^ and ~ in package.json
- Scaling Node.js for Robust Multi-Tenant Architectures
- 6 Common Mistakes in Domain-Driven Design (DDD) with Express.js
- 10 Performance Enhancements in Node.js Using V8
- Can Node.js Handle Millions of Users?
- Express.js Secrets That Senior Developers Don’t Share
Read more blogs from Here