Running a Cron Job with Node.js and Heroku

The docs for the Heroku Scheduler Add-on are pretty weak when it comes to Node.js - so here is the result of several hours of trial and error.

November 28, 2018
3 minute read

All the answers I found on this subject seems to be pretty dated, so I thought I would help anyone out there looking for a proper answer on how to setup a scheduled task to run with a Node.js project running on Heroku. I myself needed a task to run on my node server every 10 minutes, and I didn't necessarily want to do it with something as complicated as a serverless function. I thought that since my actual application is running on Heroku, then my task should be able to come from the server itself.

The top answer on Stack Overflow explains that you can run the task with a file that has no extension, like this: <project_root>/bin/say_hello which is true. However this isn't really the case. There are two ways to run a node file from the scheduler.

This guy had a close answer, but didn't fully explain it. This led to me to Heather Booker's blog where she also shed some light on how to tackle this problem.

Some helpful things to know:

Assuming you already have the Heroku CLI installed...

  1. Run the command heroku run bash to access the server's command line.
  2. When finished with bash, type exit then hit enter to exit the server terminal.
  3. Run the command heroku logs --tail to view the server logs of your app.

Start with Your JS file

Create a file called worker.js. In that file, just put a simple console.log message so we can test to make sure everything works.

Push it to the Server

You can add the worker.js file to a folder called bin. The path to the file will be bin/worker.js. Push this file to your root directory on Heroku.

You can test if the file works by logging into the server with heroku run bash then type in node bin/worker.js.

Set up the Scheduler

  • In your Heroku dashboard, under the Resources tab, you'll find the add-ons section. Search for Heroku Scheduler then add it.
  • Once it's added, you can add a new job.
  • Add the command: node bin/worker.js and you're all set!

To confirm it's working, wait until a job has actually run (you'll see this under the "Next Due" time) and run the heroku logs --tail command. In the logs you should see your message that logged from the worker.js file.