How to schedule tasks in Node.js

Scheduling recurring tasks is essential for automation, from database cleanups to periodic data synchronization and report generation. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented task scheduling in Node.js backends throughout my 11 years of server-side development. The most straightforward approach is using the node-cron package, which provides a simple cron-like syntax for scheduling tasks. This method offers flexible scheduling without external dependencies or system cron configuration.

Use node-cron to schedule tasks with cron expressions.

const cron = require('node-cron')

cron.schedule('0 0 * * *', () => {
  console.log('Running daily cleanup at midnight')
  // Cleanup logic here
})

cron.schedule('*/15 * * * *', () => {
  console.log('Running every 15 minutes')
  // Sync logic here
})

cron.schedule('0 9 * * 1', () => {
  console.log('Running every Monday at 9 AM')
  // Weekly report logic here
})

Here the cron.schedule method takes a cron expression and callback function. The first schedule runs daily at midnight (0 0 * * *), the second runs every 15 minutes (*/15 * * * *), and the third runs every Monday at 9 AM (0 9 * * 1). Tasks execute automatically in the background while your Node.js application runs.

Best Practice Note:

This is the approach we use in CoreUI backend services for scheduled maintenance tasks and data processing. Always wrap task logic in try-catch blocks to prevent unhandled errors from crashing your application, and consider using task queues like Bull for complex scheduling requirements or distributed 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.
How to Add a Tab in HTML
How to Add a Tab in HTML

How to loop through a 2D array in JavaScript
How to loop through a 2D array in JavaScript

How to Remove Elements from a JavaScript Array
How to Remove Elements from a JavaScript Array

How to Manage Date and Time in Specific Timezones Using JavaScript
How to Manage Date and Time in Specific Timezones Using JavaScript

Answers by CoreUI Core Team