0
我有一个函数可以随机的时间间隔向数据库中写入数据。它使用随机超时递归调用自身。如何在Node.js中在后台运行函数
但它目前当然会干扰请求/响应周期,这就是为什么我希望它成为后台任务。
如何在Node.js的后台运行function
?我遇到了npm模块kue
,但不明白如何使用它来使该功能在后台运行。
编辑:我创建了一个文件bgTask.js
有迁此功能:
var randomstring = require('random-string');
var Thing = require('./thing.model');
var autoCreate = function(){
console.log("THING CREATED AUTOMATICALLY")
var randomNumb=0;
clearTimeout(randomNumb);
randomNumb = (Math.random()* (10-5) + 5).toFixed(0);
console.log("random number", randomNumb)
var randomThing =randomstring({
length: randomNumb,
numeric: false,
letters: true,
special: false
});
console.log("ranfom thing", randomThing)
Thing.create({
name: randomThing,
readByUser: false
}, function(err, thing) {
console.log("THING IS", thing)
setTimeout(autoCreate, randomNumb * 1000);
});
}
setTimeout(autoCreate, 10*1000);
它看起来像上面。
在API的我的控制器文件,我有这行代码:
var myBgTask = require('child_process').fork('./bgTask.js');
但我得到一个错误,指出:
Error: listen EADDRINUSE :: 5858
我该如何解决这个问题?
您看到什么类型的干扰请求? –
你可以使用['child_process'](https://nodejs.org/api/child_process.html)。 'child_process.fork()'允许你异步执行.js文件。 – Shanoor
@DavinTryon:我在帖子上发生连接错误,并把请求放在客户端/结束。 –