Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have my NodeJS app run in a loop for ever

Tags:

node.js

events

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();
like image 427
springloaded Avatar asked Apr 28 '16 02:04

springloaded


2 Answers

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.

like image 163
AJS Avatar answered Oct 06 '22 00:10

AJS


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();
like image 22
Nivesh Avatar answered Oct 06 '22 01:10

Nivesh