Search code examples
node.jscoffeescriptcroncron-task

cron fires callback function immediately instead of at designated time


I'm defining a cron job and giving it a callback function to send emails. However, instead of firing at the specified time, it fires immediately when my application is run and fails to fire at the specified time given. Is there something wrong with my cron expression? I wanted it to fire at 9:42 pm to test it. The idea is to have this function fire at the same time everyday.

Relevant coffeescript code:

cron = require 'cron'
...
cronJob = cron.job('0 42 21 * * *', sendEmails())
cronJob.start()

Solution

  • Your problem is that you're calling sendEmails when you call cron.job when you're supposed to be giving cron.job a reference to the function. The parentheses on sendEmails in here:

    cron.job('0 42 21 * * *', sendEmails())
    # ----------------------------------^^
    

    call the function. You want to say:

    cron.job('0 42 21 * * *', sendEmails)