Luke Oliff.

TIL: Scheduling Recurring Tasks With node-cron

·TIL·1 min read·Luke Oliff

Cron jobs are not just for system administration. You can run scheduled tasks in Node.js without touching the system crontab.

const cron = require('node-cron')

cron.schedule('0 9 * * 1-5', () => {
  console.log('Running weekday task at 9am')
})

The first argument is a cron expression: minute, hour, day of month, month, day of week. The second is the callback to run.

I used this for content syndication tools at Vonage. Every morning at 8am a cron job checked for new blog posts and cross posted them to dev.to and Medium. No external scheduler, no CI pipeline, just a long running Node process.

Can I run tasks every N seconds?

node-cron supports expressions like */5 * * * * * for every 5 seconds using a six field syntax. Standard cron uses five fields.

What if the process restarts?

Scheduled tasks are in memory. Restart the process and the schedule starts again. For persistent scheduling combine with a database flag or use system cron.