mche mche - 3 years ago 66
Javascript Question

Setting a datetime / timer in Node

Say I wanted to set up a timed service to run via Node. Would I really be using the

to run ~every minute or so to check if the time matches? Is there a better way to go about this?

More specifically, I'd like to set up a service that's given a time of a day, at that time it'll fire off an email.

In pseudocode:


// using moment.js for time formatting
var isItTime = new moment().format("HH:mm") === "04:00";

if( isItTime ) {

}, 60 * 1000);

Is there a better or more standardized way?

Answer Source

I'm not normally one to recommend packages, but since this is a relatively common pattern, ie search for "node cron job", I would recommend leveraging a package for scheduling repeating tasks. One such example is node-schedule.

See this quote from the docs as to why I recommend it, (emphasis mine):

Node Schedule is for time-based scheduling, not interval-based scheduling. While you can easily bend it to your will, if you only want to do something like "run this function every 5 minutes", you'll find setInterval much easier to use, and far more appropriate. But if you want to, say, "run this function at the :20 and :50 of every hour on the third Tuesday of every month," you'll find that Node Schedule suits your needs better.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download