-1

I am creating a node app in which for each request I am calling a function at regular intervals

app.js

var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');

var app = express();

const PORT = process.env.port || 1234

app.listen(PORT, () => { console.log(`Server running at ${PORT} ...`)} );   



var router = express.Router();

function ping(i, appURL) 
{
    request(appURL, function (error, response, body) {
         console.log('i:', i ++ ,'url: ', appURL, 'statusCode:', response && response.statusCode, 'Time: ', new Date()); 
    });
}

router.route('/')
    .post(function(req, res) {
        var appURL = req.body.url;
        var i = 1;
        ping(i, appURL);
        setInterval(function() {
            request(appURL, function (error, response, body) {
                ping(i, appURL);
            });
        }, 1800000);
        res.end('Success');
    });

app.use(bodyParser.json());
app.use('/', router);

Whenever there is a request to the app, I am calling the ping function for every 30 minutes.

Does a node app can handle more setInterval()?

Is it good to use setTimeout() instead of setInterval()?

1 Answers1

2

How many setInterval() functions can a node app handle?

nodejs is designed to handle a lot of timers (hundreds of thousands at least).

So, a small number of setInterval() timers is perfectly fine. But, adding a new interval that runs forever every time a route is hit seems like a bug to me as they will just accumulate indefinitely until your server is restarted.

If you describe in more detail what problem you're really trying to solve, we can help you find an appropriate way to code that. What you have now, just runs a request() over and over again and does not do anything with a result and every time your route is hit again it starts the whole thing running again so you have multiple instances of it running over and over again. That looks like a faulty design.

Here's another answer that points to info about how timers are designed in nodejs: How many concurrent setTimeouts before performance issues?

Is it good to use setTimeout() instead of setInterval()?

It won't change your scalability either way. There are different design reasons to use repeated setTimeout() vs. setInterval(), but neither will change your core question.

jfriend00
  • 683,504
  • 96
  • 985
  • 979