最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make a request every one minute with Node.js - Stack Overflow

programmeradmin3浏览0评论

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: "",
    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

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

Share Improve this question asked May 30, 2015 at 3:10 Daniela MoraisDaniela Morais 2,2378 gold badges30 silver badges54 bronze badges 1
  • 1 look at JS setTimeout or setInterval functions – Seth McClaine Commented May 30, 2015 at 3:14
Add a comment  | 

1 Answer 1

Reset to default 25

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)
发布评论

评论列表(0)

  1. 暂无评论