如何在网络服务器 运行 时每 2 分钟调用一个函数?
How to call a function each 2 min while webserver is running?
我的问题是当网络服务器 运行 时每两分钟调用一个函数。所以我的服务器是这样启动的:
app.listen(1309, function(){
console.log("server is listening");
doSomething();
});
这是我的函数 doSomething()
var doSomething = function(){
while(true) {
sleep.sleep(10);
console.log("hello"); //the original function will be called here as soon as my code works :P
}
};
所以是的,该函数每 10 秒打印一次(10 秒
因为测试用例,不想在启动我的网络服务器后等待 2 分钟 atm),但它无法接收任何获取请求。 (用 console.log 测试过)
我在没有这个功能的情况下试过了,它收到了。所以我猜 while 循环会阻塞服务器的其余部分。我怎样才能在服务器 运行 时每 2 分钟(或 10 秒)调用一次此函数并且不会错过任何对它的请求?
您需要使用setInteval函数:
const 2mins = 2 * 60 * 1000;
var doSomething = function() {
setInterval(function() {
console.log("hello");
}, 2mins);
}
我的问题是当网络服务器 运行 时每两分钟调用一个函数。所以我的服务器是这样启动的:
app.listen(1309, function(){
console.log("server is listening");
doSomething();
});
这是我的函数 doSomething()
var doSomething = function(){
while(true) {
sleep.sleep(10);
console.log("hello"); //the original function will be called here as soon as my code works :P
}
};
所以是的,该函数每 10 秒打印一次(10 秒 因为测试用例,不想在启动我的网络服务器后等待 2 分钟 atm),但它无法接收任何获取请求。 (用 console.log 测试过)
我在没有这个功能的情况下试过了,它收到了。所以我猜 while 循环会阻塞服务器的其余部分。我怎样才能在服务器 运行 时每 2 分钟(或 10 秒)调用一次此函数并且不会错过任何对它的请求?
您需要使用setInteval函数:
const 2mins = 2 * 60 * 1000;
var doSomething = function() {
setInterval(function() {
console.log("hello");
}, 2mins);
}