node.jsherokuscheduler

Using Heroku Scheduler with Node.js


There is literally no tutorial about using Heroku Scheduler with Node.js. Assume that I have a function called sayHello() and I would like to run it every 10 mins. How can I use it in controller. In ruby you write rake function_name() however no explanation made for Node. Can I write '/sayHello' or I should do extra configuration?


Solution

  • Create the file <project_root>/bin/say_hello:

    #! /app/.heroku/node/bin/node
    function sayHello() {
        console.log('Hello');
    }
    sayHello();
    process.exit();
    

    Deploy to Heroku and test it with $ heroku run say_hello then add it to the scheduler with task name say_hello.

    Explanation

    Take say_hello.js as an example of a Node.js script that you would normally run using $ node say_hello.js.

    Turn it into a script by

    1. removing the .js ending
    2. inserting the 'shebang' at the top: #! /app/bin/node [1][2]
    3. moving it into the bin directory [3]

    [1] Read about the shebang on Wikipedia.
    [2] The node executable is installed in app/bin/node on Heroku. You can check it out by logging into bash on Heroku with $ heroku run bash then asking $ which node.
    [3] Heroku requires scripts to be placed in the bin directory. See Defining Tasks in the Heroku Dev Center.

    I agree that the Heroku documentation for scheduling tasks is not very clear for anything other than Ruby scripts. I managed to work it out after some trial and error.