How to run cron jobs in Node.js

Running cron jobs programmatically within your Node.js application provides better control and monitoring compared to system-level cron. As the creator of CoreUI, a widely used open-source UI library, I’ve managed automated jobs in production Node.js systems throughout my 11 years of backend development. The most reliable approach is using node-cron with proper error handling and job lifecycle management. This method allows you to start, stop, and monitor jobs within your application runtime.

Use node-cron with timezone support and lifecycle controls for cron jobs.

const cron = require('node-cron')

const backupJob = cron.schedule('0 2 * * *', async () => {
  try {
    console.log('Starting database backup')
    // Backup logic here
    console.log('Backup completed successfully')
  } catch (error) {
    console.error('Backup failed:', error)
  }
}, {
  scheduled: false,
  timezone: 'America/New_York'
})

backupJob.start()

process.on('SIGTERM', () => {
  console.log('Stopping cron jobs')
  backupJob.stop()
  process.exit(0)
})

Here a cron job is created with scheduled: false to prevent automatic execution, allowing manual control with start(). The timezone option ensures the job runs at the correct time regardless of server timezone. Error handling with try-catch prevents job failures from affecting the application. The SIGTERM handler gracefully stops jobs during shutdown.

Best Practice Note:

This is the pattern we use in CoreUI enterprise backends for managing critical scheduled operations. Always log job execution and failures, consider using distributed locks for jobs in clustered environments, and implement job status monitoring with health check endpoints for production systems.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team