Create a Cron job in Node.js

Vatsal Shah
1 min readMay 16, 2020

--

Here’s a node.js snippet to create cron jobs in node.js easily. A cron job is to automatically complete recurring tasks on a set schedule.

Step 1:

Install the cron job manager module.

npm install cron-job-manager

Step 2:

Assign time pattern and cron job id:

// Ref: Set Cron job: https://crontab.guru/
const timerPattern = "01 00 * * *"; // everyday at 12:01 am
const cronJobId = "cronJobId";

Step 3:

Initiate the cron job!

// Initiate Cron Job
manager.start(cronJobId);

Step 4:

Add a cron job to the manager which helps to update, delete to check the status of scheduled tasks.

// Add Cron job to manager
manager.add(cronJobId, timerPattern, () => {
logger.info("CronJob is executed.");
functionToExecute();
});

Final Code:

Here’s the full code snippet:

Author

Vatsal Shah

PORTFOLIO | GITHUB | BLOG

If you like my stuff and hate spam, I can send my upcoming articles to your inbox. One-click unsubscribe anytime — Click here to join my newsletter 💌

If you’re feeling generous today, you can buy me a coffee

--

--

Vatsal Shah
Vatsal Shah

Written by Vatsal Shah

Intrapreneur, Machine Learning | AI | Software Engineer | IoT | Voice Applications

No responses yet