Home > other >  Randomly run a node script file
Randomly run a node script file

Time:01-23

I am using forever to keep a node script running:

forever start script1.js

But I need to run the files randomly...

for example:

  1. Run node script1.js
  2. Run node script2.js
  3. Run script3.js

...

Is there any way I can have a master.js file which randomly runs these script files each time? and then I can use this master with forever.

forever start master.js > which runs script1.js script2.js etc randomly.

CodePudding user response:

First things first, define "randomly". Do you mean every set amount of time a random file is run? Second, do you wish for the worker scripts' lives dependent on the master?

If i get what you mean, then this is simple enough

let {fork} = require("child_process")
setInterval(() => {
    let scripts = ["script1.js", "script2.js", "script3.js"] //you can provide full path
    let randomScript = scripts[Math.floor(Math.random() * Math.floor(scripts.length))]
    fork(randomScript) //optionally, you can inherit stdio if you wish to see output
}, 20000) //time period in ms, in this case 20 seconds

I used fork here, which will only work with js scripts, but if you wish to execute a file or spawn another process I would suggest looking here

CodePudding user response:

Create a master.js with code

 const {exec} = require('child_process');
 function getRandomNumberBetween(min,max){
    return Math.floor(Math.random()*(max-min 1) min);
 }
 switch (getRandomNumberBetween(1,3)) {
    case 1:
        exec('forever start script1.js')
        break;
    case 2:
        exec('forever start script2.js')
        break;
    case 3:
        exec('forever start script3.js')
        break;
    default:
        break;
    }

run the file node master

  •  Tags:  
  • Related