gpt4 book ai didi

javascript - 添加代码智能到nodejs中的rest api链接

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:37 25 4
gpt4 key购买 nike

我有一个nodejs应用程序,它监听对其进行的休息调用。但是,我想为我的代码添加一些智能。

例如,我只想每 5 分钟为给定的调用执行一个函数。因此,即使有人每秒或每分钟调用一次其余链接,我也只想每 5 分钟执行一次。我如何实现这种灵 active ?

随机调用nodejs服务器

http:// abc.com/pager/a     is called 100 times within 5 minutes should only execute the function once for the first call and must resume executing the function after 5 minutes 
http:// abc.com/pager/b
http:// abc.com/pager/c

示例代码

app.post('/pager/:room',function(req,res){

var room = req.params.room;

if( room == 'a'){
console.log("Room A called");
//execute function once every 5 minutes only for room a
func1(room)
}

else if( room == 'b'){
console.log("Room B called");
//execute function once every 5 minutes only for room b
func1(room)
}

else if( room == 'c'){
console.log("Room C called");
//execute function once every 5 minutes only for room c
func1(room)
}


});

最佳答案

这是一个通用函数,它返回另一个函数,该函数在调用后将自身禁用指定的毫秒数。

function tempDisableAfterCall(fn, ms) {
var timeToReset = 0;

return function() {
var currentTime = new Date().getTime();
if (currentTime < timeToReset) {
return;
} else {
timeToReset = currentTime + ms;
fn.apply(this, arguments);
}
}
}

// Function that will be temporarily disabled
function printNumber(num) {
console.log(num)
}

// Create a modified function that is disabled after it has been called
var printNumberWait = tempDisableAfterCall(printNumber, 5000);

// Call the function every 500 ms, but you will only see a log every 5 seconds
setInterval(function() {
printNumberWait(new Date().getTime());
}, 500)

关于javascript - 添加代码智能到nodejs中的rest api链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com