Cron Jobs in Node.js: The Practical Guide Nobody Gave Me
I spent 3 days learning things about cron in Node.js that should have been documented somewhere. Here is everything I wish I had known.
The Basics Everyone Shows You
const cron = require('node-cron');
// Run every 5 minutes
cron.schedule('*/5 * * * *', () => {
console.log('Running every 5 minutes');
});
// Run daily at 9 AM
cron.schedule('0 9 * * *', () => {
console.log('Good morning!');
});
Simple enough. node-cron has 50k+ weekly downloads for a reason.
But here is what the tutorials do NOT tell you.
1. Your Process Will Crash (And Your Cron Jobs Die)
This is the #1 thing that bit me:
// app.js
const cron = require('node-cron');
cron.schedule('*/5 * * * *', async () => {
// If THIS throws, the entire process dies
const data = await fetchSomethingThatMightFail();
processData(data); // Can also throw
});
When an unhandled exception occurs inside your cron
Discussion
Your thoughts matter!
Your input is valuable—be the first to share it!