Facebook Pixel

How do I create a PM2 cron script?

Create a standalone script that connects to the database, performs the task, and exits with process.exit(0) on success or process.exit(1) on failure. Load dotenv, connect to MongoDB, run the task, disconnect, and exit. PM2 will run it at the scheduled cron time.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Using PM2 cron-start for Recurring Tasks Server-Level Scheduling

Use pm2 start script.js --cron '0 0 * * *' --name task-name. Or define in ecosystem.config.js with cron: '0 0 * * *' and autorestart: false. PM2 runs the script at the scheduled time, captures logs, and manages restarts.

Use PM2 cron for independent tasks (backups, log rotation, system checks) that don't need app context. Use node-cron for tasks integrated with your app (using models, cache, database connections) that should stop when the app stops.

Use pm2 logs task-name to view logs of a specific cron job. Use pm2 logs to view all logs. Use pm2 status to see all processes including cron jobs and their last execution status.

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.