While system-level cron jobs are powerful, Node.js developers often prefer keeping their scheduling logic within the application. node-cron
is a popular and flexible library that lets you create cron jobs in pure JavaScript, using familiar cron syntax.
Step 1: Install node-cron
npm install node-cron
Step 2: Basic Job Example
Here’s a simple job that runs every minute:
const cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('Running task every minute');
});
Step 3: More Cron Patterns
node-cron
follows standard 5-field cron syntax: minute hour day month weekday
-
0 9 * * *
→ Every day at 9:00 AM -
*/10 * * * *
→ Every 10 minutes -
0 0 * * 0
→ Every Sunday at midnight
Step 4: Validation and Error Handling
node-cron
will throw an error if the cron pattern is invalid. You can wrap tasks in try-catch for safe execution:
cron.schedule('*/5 * * * *', () => {
try {
// your task logic
} catch (err) {
console.error('Cron job failed:', err);
}
});
Step 5: Controlling Jobs
You can start/stop jobs manually as well:
const task = cron.schedule('* * * * *', () => {
console.log('Controlled task');
});
task.stop(); // pause the job
task.start(); // resume it
Pros & Cons of Using node-cron
-
✅ Pros:
- Familiar cron syntax with JavaScript integration
- Works entirely in code, no external setup
- Supports manual control of jobs (pause/resume)
-
⚠️ Cons:
- Jobs are tied to the Node process — if it restarts, so does the schedule
- No built-in persistence or retries
- Less suitable for distributed task coordination
Alternatives
- Agenda.js – Uses MongoDB for persistence, good for background jobs
- BullMQ – For Redis-backed queue-based job handling
- PM2 – Process manager that can help keep cron tasks alive and robust
Conclusion
node-cron
is an excellent choice for quick and readable task scheduling inside a Node.js app. It's lightweight, flexible, and doesn’t rely on external systems — perfect for internal timers, notifications, or log rotation.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift