Many backend tasks must occur on automated schedules: generating midnight invoice reports, expiring inactive user trials, emailing daily digests, and cleaning temporary directories. In this tutorial, you will master automated task scheduling using node-cron.
┌────────────── minute (0 - 59)
│ ┌──────────── hour (0 - 23)
│ │ ┌────────── day of month (1 - 31)
│ │ │ ┌──────── month (1 - 12)
│ │ │ │ ┌────── day of week (0 - 7, 0 and 7 are Sunday)
│ │ │ │ │
* * * * *
node-cronnpm install node-cron
// scheduler.js
const cron = require('node-cron');
const fs = require('fs');
console.log('[SCHEDULER INITIALIZED] Watching automated tasks...');
// 1. Run every minute (For testing)
cron.schedule('* * * * *', () => {
console.log('[CRON 1 MINUTE] Heartbeat check:', new Date().toLocaleTimeString());
});
// 2. Run every midnight at 00:00 (Daily database cleanup)
cron.schedule('0 0 * * *', async () => {
console.log('[MIDNIGHT TASK] Cleaning expired authentication tokens...');
// await Token.deleteMany({ expiresAt: { $lt: new Date() } });
});
// 3. Run every Monday at 9:00 AM (Weekly student report)
cron.schedule('0 9 * * 1', () => {
console.log('[WEEKLY TASK] Generating university attendance summary...');
});
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Integrate background jobs with RabbitMQ or Redis.
Automate daily log rotation and file cleanups.
Ensure cron jobs don't block main event thread.