Step 1: Create a NodeJs application.
Initialize a new app with npm and install the Express package. Make sure NodeJs is installed on your machine.
- npm init
- npm i express
Step 2: Set up the Express server
- Create the app.js file (note that some people prefer to call this file server.js)
- Configure the port and set up the listener
Step 3: Add the node-cron npm package to the application
- npm i node-cron
Step 4: Set up a folder for your scheduled jobs
- Create a folder called "scheduledFunctions" or similar
Step 5: Define the logic to run your scheduled jobs
- In the folder you just set up, create a file to hold your scheduled function logic. You can also use different files for each task if you prefer.
- Configure scheduled logic
The execution frequency of your custom function is defined as the first argument to the Cron.schedule function. Note that this argument is written as a Cron Schedule Expression or crontab. I find Crontab Guru a really useful resource to play around and get comfortable with schedule expressions so you can easily set up your own.
Step 6: Configure the Express app to initialise and run the job schedules
- In the app.js file add a call to the init function(s) from your scheduled file(s).
Start the app to generate the functions and their schedules in the Cron scheduler. Your custom logic will be executed to schedule as long as the app is running.
If you liked this post, please share it!