In my Node js application due to clustering, the function is executing multiple time. How can I run a function only 1 time? Actually, want to run cron job but due to multiple execution of the function, cron is executing multiple time.
Clustering code: `
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
`
Move the call to test function to master block
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");
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments