18

I have written a NodeJS app that calls an API and posts to an endpoint only on weekdays at a specific time.

I could setup a cron job to run the app at the specified time but I'd prefer to run it with node index.js and have it run constantly, doing nothing until it's the right day and time and then going back to "sleep" until the following day.

How do I achieve that? I tried with a while loop:

while (true) {
  myApp.run();
}

Obviously that didn't go too well.

What's the right way to do it? Should I rewrite my modules to use events, so that I emit one when it's time and there is a listener that reacts to it?

--edit: To be more specific, I would like it to run in a similar way to an app that has a webserver in it. When you start the app, it's running and waiting for connections; it doesn't exit when the request & connection end, it stays running waiting for more requests & connections.

--edit 2: The reason I'd rather not use a cron is because the days and time to run on are configurable in a config.json file that the app parses. I'd rather avoid messing with cron and just change the schedule by editing the config.json file.

--edit 3: I'd like to code this myself and not use a module. My brain always hurts when trying to write an app that would run forever and I'd like to understand how it's done rather than using a module.

--edit 4: Here is what I ended up using:

function doStuff() {
  // code to run
};

function run() {
  setInterval(doStuff, 30000);
};

run();
3
  • Not much of a node person, but I imagine it has some kind of Timer you can set up. I would use one of those. Apr 28, 2016 at 2:56
  • 1
    I feeel like cron or some sort of job scheduler like resque would be better. You can always use setInterval Apr 28, 2016 at 3:00
  • You could get the current day and time, and then calculate the amount of time until the next time you want to call your API. Then use that time interval in a call to setTimeout() or setInterval() (as mentioned by Nick Tomlin above)
    – RJM
    Apr 28, 2016 at 3:02

6 Answers 6

11

well you could always use a simple setInterval:

 function execute(){
   //code to execute

 }


 setInterval(execute,<calculate time interval in milliseconds you want to execute after>);

this is a very bare-bones basic way to do it. Hope this helps.

5
  • 2
    This leads to running out of memory Apr 28, 2016 at 20:29
  • what was the interval that you had set it to?
    – AJS
    Apr 29, 2016 at 5:41
  • i think you have set your interval very low as in my testing it never gave any problems, always try to have interval around 1 sec or more if it is to run infinity.
    – AJS
    Apr 29, 2016 at 7:04
  • 1
    I used a 50 secs interval but I think my mistake was to recursively call the function to execute in the setInterval. I guess I was tired. Apr 30, 2016 at 2:35
  • 1
    No need of recursion here. Setinterval dose all the work for you.
    – AJS
    Apr 30, 2016 at 3:35
4

You can use cron module. And for time and data that you can load from your config file, without hard coding it in the code.

Example:

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();
3
  • Thank you, but I'd like to do this myself without a module to try and understand how it's done. The thing I struggle with is understanding how things like express do to have a process that always runs and waits for incoming requests Apr 28, 2016 at 11:41
  • what express does is completely different from what you want to achieve here @springloaded it starts up a HTTP server and waits for requests.
    – AJS
    Apr 28, 2016 at 12:08
  • may be this helps see the source :github.com/nodejs/node/blob/master/lib/_http_server.js#L429
    – AJS
    Apr 28, 2016 at 12:19
2

So here is how I solved it, as @AJS suggested:

function myApp() {
  while (!isItTimeYet) {
    setInterval(myApp, 59000);
  }
}

It was simpler than I thought and hopefully it doesn't leak memory.

--edit: This is wrong and leaks memory because each loop makes it one level deeper. This is the way:

function doStuff() {
  // code to run
};

function run() {
  setInterval(doStuff, 30000);
};

run();
4
  • 1
    But ain't you creating new intervals every time it loops the while? I think you do... also the set interval should be enough. Apr 28, 2016 at 20:36
  • 1
    Yes, this was wrong because it was recursively calling the function that was setting the setInterval within the setInterval. I was tired when I tried it I guess. Apr 30, 2016 at 2:36
  • Just keep it simple follow my answer
    – AJS
    Apr 30, 2016 at 3:37
  • 2
    This would reschedule do stuff at interval only once. This would work, probably not leak. While loop would require setTimeout instead.
    – Martin
    Nov 11, 2019 at 15:30
0

You could try this tool https://www.npmjs.com/package/forever. It's pretty simple to use:

Just run your script with forever start app.js,

1
  • This won't work because my script doesn't run in a loop to begin with so it would die every 500 ms, with forever restarting it all the time. Apr 28, 2016 at 10:54
0

NPM to the rescue ;)

node-schedule

0

Adding to the setInterval() approach, using setTimeout().

const sleep = (milliseconds) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), millisecond)
  })
}
const doStuff = () => {}

const main = async () => {
  while(true) {
    doStuff()
    await sleep(5000)
  }
}
(async () => {
  await main()
})()

Note: If doStuff() has promises and async code then you would need to take care of re-entry related issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.