Heroku Scheduler with Node.js Tutorial
/I recently put together a script for Bike Pretty so we could track the store's inventory over time. I did this by running a Node.js script using Heroku's scheduler every day at midnight. However, I ran into a problem along the way: Heroku's documentation on the scheduler has no Node.js examples.
Here's how you do it.
1. Write your script.
In your functional Node + Heroku dev environment create a file called scheduled-job.js and copy pasta the simple script below:
function sayHello() { console.log('Hello'); } sayHello();
Every time this script is run it will log the word "Hello".
2. Test the script.
Heroku runs scheduled jobs as One-Off Dynos. This is the same thing as using your terminal to run a given script. So let's test and see if our script works using the terminal first.
Let's do this by running the script locally. Open a terminal window in the directory of scheduled-job.js and type the command:
node scheduled-job.js
You should see the script print "Hello" in your terminal window.
3. Deploy to Heroku and test.
Do your Git adds and commits and push the script up to Heroku. Now we're ready to test.
When we're in the Heroku environment we have to append "heroku run" to our terminal commands to make them One-Off Dynos. Since the terminal command we used to run our script was "node scheduled-job.js" we can run a One-Off Dyno using this command:
heroku run node scheduled-job.js
You should see the script start up and then log "Hello" into your terminal window.
4. Setup the scheduler.
The last step is getting your script to trigger automagically at regular temporal intervals.
First install the scheduler from Heroku's addons page. If you haven't already, Heroku will also require that you enter your billing information. This would be used if your script exceeded Heroku's usage limits. But don't worry, logging "Hello" will not incur any charges.
Once the scheduler is installed you can go to your dashboard on Heroku, click your app, and then click the link for Heroku Scheduler. This will bring you to a pretty self-explanatory page where you can add new tasks to be scheduled.
Click the "Add Job" link and copy paste this command into the "Task" field:
node scheduled-job.js
Once you choose your frequency and the time of your next run you can click save and you're good to go!
5. Final testing.
After your scheduled task runs once (you will see the "Last Run" column in the scheduler change to the time and date of the last execution) you should be able to see your "Hello" in the Heroku logs.
Type the below command into your terminal window to inspect the logs:
heroku logs --tail
Congratulations! Now it's time to write a scheduled task that does something useful!