Javascript 使用 Node.js 每分钟发出一个请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30541831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:22:32  来源:igfitidea点击:

Make a request every one minute with Node.js

javascriptnode.js

提问by Daniela Morais

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

Node.js今天开始开发,我认为一个应用程序可以执行多个请求来了解服务器正常运行时间。我需要每个请求完成该函数作为一个 while 循环再次执行
是否可以在 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

PS:对不起,如果这是一个愚蠢的问题或重复

回答by

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

JavaScript 有一个setInterval函数,在 NodeJS 中也是如此。您可以将您提供的函数包装到一个setInterval循环中。

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

setInterval的论点是(callback, time),在time通过毫秒表示...所以让我们做一点数学的...

1s = 1000msand 1m = 60s, so 60 * 1000 = 60000

1s = 1000ms并且1m = 60s,这样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)