由于群集,在我的Node js应用程序中,该函数正在执行多次。我怎么能只运行一次功能?实际上,想要运行cron作业但是由于多次执行该函数,cron正在多次执行。
群集代码: `
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
// console.log('numCPUs--------',numCPUs);
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
console.log(process.pid);
}
cluster.on('exit', function (worker, code, signal) {
// handle server crashes
console.log('worker ' + worker.process.pid + ' died');
});
} else {
console.log(cluster.worker.id);
const port = process.env.PORT || 8000;
app.listen(8000);
}
(function test() {
console.log("THIS is test");
}());
OUTPUT: 4
THIS is test
1
3
THIS is test
THIS is test
2
THIS is test
`
答案 0 :(得分:1)
将对测试的调用移至主块
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
test(); // calling test function moved to here
// Fork workers.
// console.log('numCPUs--------',numCPUs);
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
console.log(process.pid);
}
cluster.on('exit', function (worker, code, signal) {
// handle server crashes
console.log('worker ' + worker.process.pid + ' died');
});
} else {
console.log(cluster.worker.id);
const port = process.env.PORT || 8000;
app.listen(8000);
}
// implementing the function only
function test () {
console.log("THIS is test");
}