MyInternships.in

Testing, Performance & Deployment

Node.js Cron Jobs and Scheduled Tasks

Scheduled work — nightly reports, cleanup, email digests — can run inside Node with node-cron, or outside it with the system crontab. Which you choose depends on whether the job must share application code.


What is Cron Jobs and Scheduled Tasks in Node.js?

Scheduled work — nightly reports, cleanup, email digests — can run inside Node with node-cron, or outside it with the system crontab. Which you choose depends on whether the job must share application code.

Cron Jobs and Scheduled Tasks example

In-process scheduling
JavaScript
import cron from 'node-cron';

// 02:30 every day, in a specific timezone
cron.schedule('30 2 * * *', async () => {
  try {
    await archiveExpiredJobs();
    logger.info('archive job complete');
  } catch (err) {
    logger.error({ err }, 'archive job failed');
  }
}, { timezone: 'Asia/Kolkata' });

System crontab alternative

Terminal
# m h dom mon dow  command
30 2 * * *  cd /var/www/api && /usr/bin/node scripts/archive.js >> /var/log/archive.log 2>&1

Key points to remember

  • Always set the timezone explicitly — servers commonly run in UTC.
  • Wrap the job body in try/catch; an unhandled rejection can kill the process.
  • Under clustering, guard so only one worker runs the job.
  • Long or critical jobs belong in a queue such as BullMQ, not a cron callback.

Common mistakes with Cron Jobs and Scheduled Tasks

  • Running an in-process cron under PM2 cluster mode, so every worker executes it.
  • Assuming server time is local time and scheduling five and a half hours off.

Node.js Cron Jobs and Scheduled Tasks— Interview Questions & FAQs

Should I use node-cron or the system crontab?+

node-cron when the job needs the application’s code, models and connections. System crontab for standalone maintenance scripts, and because it keeps running even if the app is restarting.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships