Scheduled Jobs with node-cron
Schedule recurring tasks with cron jobs. Automate cleanups and reports.
Scheduled Jobs with node-cron
What are Cron Jobs?
Cron jobs run code at specific times automatically: - Every day at midnight - Every Monday at 9 AM - Every 5 minutes - First day of each month
Setup
```bash npm install node-cron ```
Basic Usage
```javascript const cron = require('node-cron');
cron.schedule('* * * * *', () => { console.log('Running every minute'); });
cron.schedule('0 0 * * *', () => { console.log('Running daily at midnight'); performDailyCleanup(); });
cron.schedule('0 9 * * 1', () => { console.log('Running every Monday at 9 AM'); sendWeeklyReport(); }); ```
Cron Syntax
``` * * * * * │ │ │ │ │ │ │ │ │ └─ Day of week (0-7, 0 and 7 = Sunday) │ │ │ └─── Month (1-12) │ │ └───── Day of month (1-31) │ └─────── Hour (0-23) └───────── Minute (0-59)
Examples: '0 0 * * *' → Every day at midnight '*/5 * * * *' → Every 5 minutes '0 9 * * 1-5' → Weekdays at 9 AM '0 0 1 * *' → First day of month '0 */6 * * *' → Every 6 hours ```
Real Example: Delete Old Logs
```javascript cron.schedule('0 2 * * *', async () => { console.log('Cleaning old logs...'); const thirtyDaysAgo = new Date(); thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30); await Log.deleteMany({ createdAt: { $lt: thirtyDaysAgo } }); console.log('Cleanup complete'); }); ```
Real Example: Daily Report
```javascript cron.schedule('0 8 * * *', async () => { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const stats = { newUsers: await User.countDocuments({ createdAt: { $gte: yesterday } }), orders: await Order.countDocuments({ createdAt: { $gte: yesterday } }) }; await sendEmailReport(stats); }); ```
Start/Stop Jobs
```javascript const task = cron.schedule('* * * * *', () => { console.log('Running task'); }, { scheduled: false });
task.start();
task.stop();
task.destroy(); ```
Key Takeaway
Use cron for recurring tasks. Understand cron syntax. Handle errors in jobs. Consider timezone for global apps. Use Bull queue for complex job management.