-2

I'm trying to create a batch file to run a program at random, but it does not work how I can make batch file work?

set /a timeout=%RANDOM% * 21 / 32768 + 20
timeout %timeout%
notepad.exe
Gerhard
  • 22,678
  • 7
  • 27
  • 43
Arslan
  • 5
  • 2
  • this script runs only every 20 seconds the program should do it randomly at any second – Arslan Aug 17 '18 at 07:23
  • `echo set /a timeout=%RANDOM% * 21 / 32768 + 20 & timeout /t %timeout% & notepad.exe` see http://stackoverflow.com/questions/41030190/command-to-run-a-bat-file/41049135#41049135 – CatCat Aug 17 '18 at 07:31
  • 2
    _"it does not work"_ is a horrible example of an issue. What does it do, or not do? – Gerhard Aug 17 '18 at 07:46
  • @CatCat, you'd need [delayed expansion](http://ss64.com/nt/delayedexpansion.html) if you want to write it all in a single line! – aschipfl Aug 17 '18 at 08:12
  • Is your code placed in a paranthesised block, like the `do ( ... )` clause of a [`for` loop](http://ss64.com/nt/for.html), for example? – aschipfl Aug 17 '18 at 08:13

1 Answers1

1

Your description of the problem is unclear. it is not working" can mean anything. The code you posted works. and does exactly what you asked it to do:

set /a timeout=%RANDOM% * 21 / 32768 + 20
timeout %timeout%
notepad.exe

Based on you comment however, "this script runs only every 20 seconds the program should do it randomly at any second" I am assuming you want to loop the code, like this:

:loop
set /a timeout=%RANDOM% * 21 / 32768 + 20
timeout %timeout%
notepad.exe
goto :loop

That however is dangerous, if you open notepad too many times (especially on low memory devices), the pc can become unresponsive. So instead, do a process count and only start new instances if in the number of processes are not met:

:loop
set /a timeout=%RANDOM% * 21 / 32768 + 20 & timeout %timeout%
for /f "tokens=1,*" %%i in ('tasklist ^| find /I /C "notepad.exe"') do set var=%%i
if %var% LSS 10 start notepad.exe
goto :loop

This example will loop endlessly, but it will only start notepad.exe if 10 or less instances are running. This means a maximum of 10 Notepad sessions allowed. The number after LSS can be increased/decreased.

Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • I solved the problem ,now the script works really random – Arslan Aug 17 '18 at 09:03
  • 3
    Everytime I hear about randomness not working as expected, I can't help thinking about this Dilbert strip: https://i.pinimg.com/originals/cc/3d/66/cc3d66aaf378fa9b98d8413be201f64b.gif – Julio Aug 17 '18 at 11:50