Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
Randomly run a node script file

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!