Facebook Pixel

How do I use node-cron in Node.js?

Install with npm install node-cron. Use cron.schedule('0 0 * * *', () => { ... }) to run a task daily at midnight. The first argument is a cron expression, the second is the callback. Use task.stop(), task.start(), and task.destroy() to manage the task.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Using node-cron for Scheduled Tasks in Node.js Syntax and Examples

Every minute (* * * * *), every 15 minutes (*/15 * * * *), every hour (0 * * * *), daily at midnight (0 0 * * *), weekdays at 9 AM (0 9 * * 1-5), every Sunday (0 0 * * 0), monthly on the 1st (0 0 1 * *), every 6 hours (0 */6 * * *).

Pass a timezone option: cron.schedule('0 9 * * *', () => { ... }, { timezone: 'Asia/Kolkata' }). This runs the task at 9 AM in the specified timezone, not the server's timezone. Useful when your users are in a different timezone than your server.

Use cron.validate('0 0 * * *') which returns true for valid expressions and false for invalid ones. Always validate user-provided cron expressions before scheduling to prevent runtime errors.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.