我需要 NodeJs API 来继续在 mongodb 中创建随机数据。
我避免从客户端调用它,因为这应该完全在后端发生。
var autoCreate = function(){
var randomNumb = (Math.random()* (10-0) + 0).toFixed(0);
var randomThing = randomstring.generate({
length: randomNumb,
charset: 'alphabetic'
});
Thing.create({
name: randomThing,
readByUser: false
}, function(err, thing) {
if(err) { return handleError(res, err); }
});
setInterval(function() {
autoCreate();
}, randomNumb*1000);
}
但是我第一次如何以及在哪里调用这个函数。在我的 Node API 文件/ Controller 中,我不能只编写 autoCreate()
,它会损坏。
正确的做法是什么>
最佳答案
只要有一个事件的计时器,您的脚本就会继续运行。
您问题中的代码有一个小缺陷,因为每次调用函数本身时它都会调用 setInterval
,但函数本身永远不会被调用。
这意味着它还没有启动,如果你要启动它,你将不断添加新的间隔,直到进程、数据库进程或整个系统崩溃。
使用setInterval
的示例
function ping() {
console.log('ping');
}
setInterval(ping, Math.random() * 1000);
只需以随机间隔开始 ping
-ing(其中随机时间生成一次并用作 ping
之间的间隔)
使用 setTimeout
的示例(这似乎是您想要的)
function ping() {
clearTimeout(timer);
console.log('ping');
timer = setTimeout(ping, Math.random() * 1000);
}
// ensure the timer variable exists in the global scope
var timer;
ping();
在此示例中,您需要自己开始 ping
,它会以随机间隔不断调用自身。
关于javascript - 保持 Node js 函数运行而不使用前端的任何调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507226/