[英]Make a request every one minute with Node.js
我今天開始在Node.js
開發,我認為一個應用程序可以執行多個請求來了解服務器的正常運行時間。 我需要每個請求完成,函數再次作為while循環執行。
是否可以在Node.js中執行此操作?
我的基本代碼
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:對不起,如果這是一個愚蠢的問題或重復
JavaScript有一個setInterval
函數,同樣在NodeJS中。 您可以將提供的函數包裝到setInterval
循環中。
setInterval
的參數是(callback, time)
,其中time
以毫秒表示...所以讓我們做一些數學...
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.