Create and run scheduled ‘jobs’ with Node.js 🕘⚙️

Kelvin Graddick · 1 minute read ·     
Did you know that you can quickly create and run scheduled ‘jobs’ with Node.js? 🕘⚙️

Create and run scheduled ‘jobs’ with Node.js

I needed to create a scheduled/repeated job that sends an email digest to my app users once a day. Typically, I use a PHP script and Windows Server Task Scheduler to set something like this up.
This time I decided to learn and try Node.js to set up the same thing. It works great!

What I did:



1. Set up a new Node.js project/application with both the Express.js (web framework) and Node Cron (task scheduler) packages installed



Node.js project with Node Cron task scheduler package

2. Wrote the logic for the task: this includes MongoDB databases calls to retrieve the user emails and match them with a lost of jobs for the day, as well as sending an email (SendGrid SDK/API) to each user with the job digest



Node.js cron job with MongoDB database and SendGrid emailing

3. Created the schedule for the task using the cron expression syntax, e.g. ‘0 9 * * *’ (every day at 9AM)



schedule for the task using the Node cron expression syntax

4. Deployed the service to a server via Github Actions CI/CD; automated builds/deployments



Node.js cron job run

I received my first email from the service/job the next day after I deployed it!

email from Node cron service/job

⁉️ Have you ever needed to code and setup a scheduled job for something? If so, how did you do it?

Want to share this?