Using 'cron' module in node.js on heroku server

392
January 04, 2017, at 03:32 AM

I am using cron in node.js to schedule a function that sends text messages at user-determined times. It works on my local server, but when i deploy to heroku the functions never get called.

Answer 1

On Heroku you may need to use the Heroku Scheduler.

See: https://devcenter.heroku.com/articles/scheduler

Answer 2

I'll elaborate a little bit more on what @rsp said above, so that if anyone else finds this question they'll understand why using Heroku Scheduler is the correct answer here.

When you're running software on Heroku, what happens is that Heroku will take your project, and run it on a random dyno (server) in the Heroku collection of servers on Amazon.

For a number of reasons (including to help distribute application load evenly across a large number of Amazon servers), Heroku will periodically move your dyno from one Amazon server to another. This happens many times per day, automatically, behind the scenes.

This means that your application code will be periodically restarting all the time when running on Heroku.

Now -- this isn't a bad thing from an end-user perspective, because while your application code is restarting, Heroku will queue up incoming requests, then just send them to your application once it's been successfully restarted on a new host. So to the end user, this behavior is 100% transparent.

What's important to know here, though, is that since your application code may randomly restart, you shouldn't use it to do things like run long tasks that take a while to finish, or queue up jobs to be executed in the future (what the cron module does).

Instead: Heroku created a free scheduler addon that you can use to basically say "Hey Heroku, run this Node script every minute|hour|etc."

The scheduler addon Heroku provides will reliably execute your cron task because Heroku keeps track of that timing stuff separately (outside of your application logic).

Hopefully this helps!

Rent Charter Buses Company
READ ALSO
separate data retrieval process from main file while including parts in EJS

separate data retrieval process from main file while including parts in EJS

I do <% include headerejs %> in most of my ejs files

274
Resizing and zipping image streams using archiver and sharp

Resizing and zipping image streams using archiver and sharp

I'm trying to download some images, resize them, zip them, and serve from an endpoint using streamsI'm using sharp for the resizing and archiver for the zipping

420
Node.js, Express.js and sqllite3.js

Node.js, Express.js and sqllite3.js

I have a problem with object attributes in Nodejs

438