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.
Some helpful things to know:
Assuming you already have the Heroku CLI installed...
- Run the command
heroku run bashto access the server's command line.
- When finished with bash, type
exitthen hit enter to exit the server terminal.
- Run the command
heroku logs --tailto 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
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.jsand 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.