简体   繁体   中英

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

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.

I'm using a cron job on heroku with node. Here is my top level stuff

var CronJob = require('cron').CronJob;

var dailyJob = new CronJob({
      cronTime: '0 0 0 * * *',
      onTick: function () {
        // Do daily function
        console.log('I get called 1 time a day.');
      },
      start: false
    });

dailyJob.start();

On Heroku you may need to use the Heroku Scheduler.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM