How can I perform a ping every X minutes and check the response time?

I am currently working in a big company and we have serious latency issues. This is happening in a process control system, and is unacceptable (Open a valve sometimes take 2 minutes before command start)

I want to double-check when the network team says "everything is alright on the network". So, I want to create a loop that pings the server and writes the result in a text file.

I am not a batch expert, but do you think this code is correct to use?

@ECHO OFF

:LOOPSTART

time /T
ping xxx.xx.x.x  -t >> filename.txt
sleep -m 3000

GOTO LOOPSTART

Solution 1:

Looks fine to me, but there's no need to loop it if you want to continuously ping the IP. Then you could simply do it like this:

@ECHO OFF
set IPADDRESS=x.x.x.x
ping %IPADDRESS% -t >> filename.txt

If you want to ping every X minute, use the loop:

@ECHO OFF
set IPADDRESS=x.x.x.x
set INTERVAL=60
:PINGINTERVAL
ping %IPADDRESS% -n 1 >> filename.txt
timeout %INTERVAL%
GOTO PINGINTERVAL

As you can see I replaced the sleep command with timeout. That's because sleep isn't always available on some systems whereas timeout usually is.

Missing sleep or timeout commands on your system? Don't fret. Just replace timeout with the following hack:

@ping 127.0.0.1 -n %INTERVAL% > nul

This hack simply pings your local address, and since it will respond instantly we can use this to emulate a delay in execution.

Solution 2:

For a one-liner solution use the following:

cmd /v /c "(for /l %a in () do @for /f "tokens=*" %b in ('ping -w 1000 -n 1 xxx.xxx.xxx.xxx ^| findstr "Reply Request Unknown Destination"') do @echo !DATE! !TIME! %b & timeout 3000 >NUL) > pingtestresults.txt"

NB:

  1. you can replace xxx.xxx.xxx.xxx with google.com
  2. to edit the interval change the 3000 to 60 (for 1 minutes) or 10 (for 10 seconds)
  3. if you need to put this command in batch file (.bat or .cmd), then make sure you replace % with %%