Create and Manage Cron Jobs in Node.js
Cron jobs are essential for automating repetitive tasks like sending emails, cleaning databases, or generating reports. In Node.js, you can use libraries such as node-cron or agenda to automate tasks easily. This guide walks you through creating cron jobs with node-cron, explaining patterns, advanced usage, and best practices.
Step 1: Install the Required Package
We’ll use node-cron, a lightweight and widely used scheduler.
Step 2: Set Up Your Project
Initialize a new Node.js project:
Then install node-cron:
Step 3: Create Your First Cron Job
Create index.js and add:
const cron = require('node-cron');
// Run every minute
cron.schedule('* * * * *', () => {
console.log('Cron job executed at', new Date().toLocaleString());
});
console.log('Cron job is running...');Cron Syntax Explained
Cron patterns follow this structure:
* * * * *
| | | | |
| | | | +--- Day of week (0-7)
| | | +----- Month (1-12)
| | +------- Day of month (1-31)
| +--------- Hour (0-23)
+----------- Minute (0-59)Common examples:
-
0 9 * * *— Run daily at 9:00 AM -
*/5 * * * *— Every 5 minutes -
0 0 * * 0— Every Sunday at midnight
Step 4: Run the Cron Job
Run:
You’ll see timestamps printed every minute.
Step 5: Advanced Usage
1. Create Tasks with Real Logic
cron.schedule('0 0 * * *', () => {
console.log('Running database cleanup...');
// Your cleanup logic here
});2. Add Error Handling
cron.schedule('* * * * *', async () => {
try {
console.log('Running task...');
throw new Error('Simulated error');
} catch (err) {
console.error('Cron job failed:', err.message);
}
});3. Integrate with APIs or Databases
const axios = require('axios');
cron.schedule('0 * * * *', async () => {
try {
const res = await axios.get('https://api.example.com/data');
console.log('Data fetched:', res.data);
} catch (err) {
console.error('Fetch failed:', err.message);
}
});4. Start/Stop Tasks Dynamically
const task = cron.schedule('*/10 * * * * *', () => {
console.log('Runs every 10 seconds');
});
task.stop(); // Pause
task.start(); // ResumeBest Practices
- Use dotenv for cron expressions
- Add logging (e.g., pino, winston)
- Send alerts on failures (email, Slack, Discord)
- For large workflows, use agenda, Bull, or Temporal
Conclusion
Using node-cron, you can automate workflows in Node.js with minimal setup. Whether you’re scheduling cleanup scripts, syncing external APIs, or generating reports, cron jobs make automation clean and reliable. This guide gives you everything needed to build robust scheduled tasks.