Node.js doesn’t come with native cron support, but the node-cron
package makes it easy to schedule recurring tasks using familiar cron syntax. In this guide, you'll learn how to set up robust cron jobs inside a Node.js app.
Step 1: Install node-cron
npm install node-cron
Step 2: Basic Cron Job Setup
Here’s how to create a simple job that runs every minute:
const cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('Task is running every minute');
});
Step 3: Using Real-World Cron Syntax
Want to run a job every day at 2 AM?
cron.schedule('0 2 * * *', () => {
console.log('Daily task at 2 AM');
});
Step 4: Validating Cron Expressions
node-cron
includes built-in validation so you can check if a cron string is valid before scheduling:
if (cron.validate('0 2 * * *')) {
cron.schedule('0 2 * * *', () => {
console.log('Scheduled task');
});
}
Step 5: Handling Errors and Logging
Wrap your cron jobs with proper error handling:
cron.schedule('*/5 * * * *', () => {
try {
// Your logic here
console.log('Running task...');
} catch (error) {
console.error('Task failed:', error);
}
});
Step 6: Keeping the Job Alive
If you’re not using a framework like Express, make sure your Node process stays alive:
setInterval(() => {}, 1000);
Conclusion
node-cron
offers a simple yet powerful way to manage recurring tasks in a Node.js environment. From backups to email reminders, integrating cron into your app is now seamless and code-driven.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift