Create a NodeJs application
- npm init
- npm i express
Setup the express server
- Create the app.js file (or server.js is you prefer)
Add node-cron npm package to the application
- npm i node-cron
Set up a scheduled jobs folder & files
- Create a folder called "scheduled jobs"
Create the logic of the scheduled jobs
- In the above folder, either create a single file to hold all your scheduled function logic or if preferred, a file per scheduled logic
- The scheduled logic needs to be configured as so:
- The frequency at which this logic is executed is defined by the Cron Schedule Expression defined as the first argument to the Cron.schedule function.
A really good resource to play around with schedule expressions is the Crontab Guru. Experimenting with the schedules will allow you to find what schedule expression you require.
Configure the express app to initialise the job schedules
- In the app.js file add a call to the init function(s) from your scheduled file(s).
This will generate the functions and their schedules in the Cron scheduler when your app starts up.
If you liked this post, please share it!