Daniela Morais
Daniela Morais

Reputation: 2237

Make a request every one minute with Node.js

I began to develop in Node.js today and I think an application that performs several requests to know the server uptime. I need every request completion the function is performed again as a while loop.
Is it possible to do this in Node.js?

My basic code

var http = require('http');
var request = require('request');

request({
    url: "http://www.google.com",
    method: "GET",
    timeout: 10000,
    followRedirect: true,
    maxRedirects: 10
},function(error, response, body){
    if(!error && response.statusCode == 200){
        console.log('sucess!');
    }else{
        console.log('error' + response.statusCode);
    }
});

PS : Sorry if it's a stupid question or duplicate

Upvotes: 12

Views: 35787

Answers (1)

user3117575
user3117575

Reputation:

JavaScript has a setInterval function, likewise in NodeJS. You could wrap the function you provided into a setInterval loop.

The setInterval's arguments are (callback, time), where time is represented through milliseconds... So lets do a bit of math...

1s = 1000ms and 1m = 60s, so 60 * 1000 = 60000

var requestLoop = setInterval(function(){
  request({
      url: "http://www.google.com",
      method: "GET",
      timeout: 10000,
      followRedirect: true,
      maxRedirects: 10
  },function(error, response, body){
      if(!error && response.statusCode == 200){
          console.log('sucess!');
      }else{
          console.log('error' + response.statusCode);
      }
  });
}, 60000);

// If you ever want to stop it...  clearInterval(requestLoop)

Upvotes: 25

Related Questions