Reputation: 646
Say I wanted to set up a timed service to run via Node. Would I really be using the setTimeout
or setInterval
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:
setInterval(function(){
// using moment.js for time formatting
var isItTime = new moment().format("HH:mm") === "04:00";
if( isItTime ) {
sendEmail();
}
}, 60 * 1000);
Is there a better or more standardized way?
Upvotes: 1
Views: 1164
Reputation: 4619
I'd suggest npm cron for this. You can setup any function to run at specified time from weeks to seconds. It uses cron syntax with addition of "seconds" column on left most. Here's one of the ways to configure from official docs:
var CronJob = require('cron').CronJob;
var job = new CronJob({
cronTime: '00 30 11 * * 1-5',
onTick: function() {
/*
* Runs every weekday (Monday through Friday)
* at 11:30:00 AM. It does not run on Saturday
* or Sunday.
*/
},
start: false,
timeZone: 'America/Los_Angeles'
});
job.start();
For your case of every minutes cronTime would be:
cronTime: '00 */1 * * * *'
With timeZone
option you can instruct the scheduler to run the job with respect to given timezone. This feature is very handy when running node scripts locally and online, as the script will run consistently across different timezones.
Upvotes: 1
Reputation: 650
The more common way of doing this is to take advantage of CRON jobs. A good library for doing this in node is node-cron (https://github.com/kelektiv/node-cron)
One of the big advantages to using a scheduler like CRON is that it's queue-based, which means that your jobs will easier to manage since it handles cases where a task fails or exits and has to be restarted, etc.
Upvotes: 1
Reputation: 3861
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.
Upvotes: 2
Reputation: 996
You could use either. If you used setTimeout, you could do something like this:
function myFunction(){
//perform a check
setTimeout(myFunction(), 60000);
}
Upvotes: 1