All Articles

Setting Up A Cron Job On Heroku In Node JS


cron

Problem

Summary

You want to run a cron job in Node on Heroku.

You may have tried using the node-schedule package, but can’t get it to run on Heroku. You may also have tried heroku-scheduler but it doesn’t give you the granularity you’d like.


Solution

Summary

Use cron on npm instead. It works on heroku without issue (unless you’re on an unpaid dyno, in which case you’ll need to ensure your dyno isn’t sleeping when your cron should run).

Example

const {CronJob} = require('cron');

const scheduleOne = new CronJob(
  '*/5 11,12 * * 1,2,3,4,5', // cron time
  myFunction,
);

const myFunction = () => {
  console.log('my cron is running every 5 minutes on the 11th & 12th hour of Mon, Tues, Wed, Thurs & Fri')
}

NOTE: cron doesn’t appear to accept 7 as an argument for day of week.


Problem Solved

If you have any questions you’d like to ask me about this post, feel free to reach me on Twitter or Github.

If you found this post useful and would like to show you’re appreciation, join the Brave movement and send me a tip :)