Using node-cron for Scheduled Tasks in Node.js Syntax and Examples
Learn how to use node-cron to schedule recurring tasks in your Node.js application cron expressions, scheduling patterns, and real-world examples.
Using node-cron for Scheduled Tasks
node-cron is the most popular cron scheduling library for Node.js. This guide covers syntax, patterns, and examples.
Installation
npm install node-cron
Basic Usage
const cron = require("node-cron"); // Schedule a task const task = cron.schedule("0 0 * * *", () => { console.log("Running daily task at midnight"); }); // Stop a task task.stop(); // Start a stopped task task.start(); // Destroy a task (cannot be restarted) task.destroy();
Cron Expression Reference
┌─────────────── minute (0 - 59)
│ ┌─────────────── hour (0 - 23)
│ │ ┌─────────────── day of month (1 - 31)
│ │ │ ┌─────────────── month (1 - 12)
│ │ │ │ ┌─────────────── day of week (0 - 7) (0 or 7 is Sunday)
│ │ │ │ │
* * * * *
Common Patterns
// Every minute cron.schedule("* * * * *", () => {}); // Every 5 minutes cron.schedule("*/5 * * * *", () => {}); // Every 15 minutes cron.schedule("*/15 * * * *", () => {}); // Every hour at minute 0 cron.schedule("0 * * * *", () => {}); // Every day at midnight cron.schedule("0 0 * * *", () => {}); // Every day at 9 AM cron.schedule("0 9 * * *", () => {}); // Every Sunday at midnight cron.schedule("0 0 * * 0", () => {}); // Every weekday (Mon-Fri) at 9 AM cron.schedule("0 9 * * 1-5", () => {}); // Every month on the 1st at midnight cron.schedule("0 0 1 * *", () => {}); // Every Monday, Wednesday, Friday at 5 PM cron.schedule("0 17 * * 1,3,5", () => {}); // Every 6 hours cron.schedule("0 */6 * * *", () => {}); // Every 30 seconds (node-cron supports seconds) cron.schedule("*/30 * * * * *", () => {});
Real-World Example: DevTinder Scheduled Tasks
// src/cron/index.js const cron = require("node-cron"); const User = require("../models/User"); const ConnectionRequest = require("../models/ConnectionRequest"); // 1. Daily cleanup of expired tokens cron.schedule("0 0 * * *", async () => { console.log("Cleaning up expired tokens..."); await User.updateMany( { resetPasswordExpires: { $lt: new Date() } }, { $unset: { resetPasswordToken: 1, resetPasswordExpires: 1 } } ); console.log("Token cleanup complete"); }); // 2. Send daily digest emails cron.schedule("0 9 * * *", async () => { console.log("Sending daily digest emails..."); const users = await User.find({ emailBounced: false }); for (const user of users) { const pendingRequests = await ConnectionRequest.countDocuments({ toUserId: user._id, status: "interested", createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }); if (pendingRequests > 0) { await sendEmail(user.email, "dailyDigest", { firstName: user.firstName, pendingRequests }); } } console.log("Digest emails sent"); }); // 3. Weekly inactive user cleanup cron.schedule("0 0 * * 0", async () => { console.log("Cleaning up inactive users..."); const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); await User.deleteMany({ isVerified: false, createdAt: { $lt: thirtyDaysAgo } }); console.log("Inactive users cleaned up"); }); // 4. Hourly stats logging cron.schedule("0 * * * *", async () => { const userCount = await User.countDocuments(); const connectionCount = await ConnectionRequest.countDocuments(); console.log(`Stats: ${userCount} users, ${connectionCount} connections`); });
Timezone Support
// Run at 9 AM in a specific timezone cron.schedule("0 9 * * *", () => { console.log("Running at 9 AM IST"); }, { timezone: "Asia/Kolkata" });
Scheduled Job Options
const task = cron.schedule("0 0 * * *", () => { console.log("Running task"); }, { scheduled: true, // Start immediately (default: true) timezone: "UTC", // Timezone for the cron expression name: "DailyCleanup" // Optional name for debugging }); // Start later task.start(); // Stop task.stop();
Validating Cron Expressions
// Check if a cron expression is valid const isValid = cron.validate("0 0 * * *"); console.log(isValid); // true const isInvalid = cron.validate("invalid"); console.log(isInvalid); // false
The Takeaway
node-cron provides flexible cron scheduling in Node.js. Use cron expressions (minute hour day month weekday) to schedule tasks at any interval. Common patterns include daily at midnight (0 0 * * ), every 15 minutes (/15 * * * *), and weekdays at 9 AM (0 9 * * 1-5). Use timezone option for location-specific scheduling, validate expressions with cron.validate, and use start/stop/destroy for task management.
Install with npm install node-cron. Use cron.schedule('0 0 * * *', () => { ... }) to run a task daily at midnight. The first argument is a cron expression, the second is the callback. Use task.stop(), task.start(), and task.destroy() to manage the task.
Every minute (* * * * *), every 15 minutes (*/15 * * * *), every hour (0 * * * *), daily at midnight (0 0 * * *), weekdays at 9 AM (0 9 * * 1-5), every Sunday (0 0 * * 0), monthly on the 1st (0 0 1 * *), every 6 hours (0 */6 * * *).
Pass a timezone option: cron.schedule('0 9 * * *', () => { ... }, { timezone: 'Asia/Kolkata' }). This runs the task at 9 AM in the specified timezone, not the server's timezone. Useful when your users are in a different timezone than your server.
Use cron.validate('0 0 * * *') which returns true for valid expressions and false for invalid ones. Always validate user-provided cron expressions before scheduling to prevent runtime errors.
cron.schedule returns a task object. Use task.stop() to pause the task, task.start() to resume, and task.destroy() to permanently remove it. The scheduled option (default: true) controls whether the task starts immediately.
Ready to master Node.js completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master Node.js
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

