Tuesday, 19 March 2013

Quickly wanted random delay in a batch file

Had a request at work to delay execution of  a command creating multiple connections from clients to a server, in order to upload a file. Potentially with the scheduled task in place there would be approximately 2000 connections at one time (all the clients had a fixed schedule at 7.00 am).
This was deemed as a bad idea. So the following code was born from a bit of googling



REM Initial batch code placed here

REM start of random delay code

@ECHO OFF
CLS
echo %random% > nul
set /a noofseconds=(%random%/1000)+1
echo Wait %noofseconds% seconds
ping 127.0.0.1 -n %noofseconds% -w 1000  > nul

REM batch code for to do something after delay


_______________________________________________________________

the above line set /a noofseconds=(%random%/1000)+1 potentially gives a random delay of 1 to 32 seconds, to increase it change the division to /100 i.e. set /a noofseconds=(%random%/100)+1) ,this will produce a delay 1 to 328 seconds.
Changing to /10 1 to 3277 seconds.

Hope this helps me as many others who post on the web helped me. ping 127.0.0.1 -n %noofseconds% -w 1000 > nul is well referenced on the net to.