Windows – Make batch file wait for service to start when restarting services

batchcommand lineserviceswindows

I have a batch file that frequently restarts a group of services developed in house. We are soon moving away from these to something more stable, but for the time being the services need to be restarted pretty often in order to work properly.

To simplify this I have a batch file that runs on a schedule. It looks like this:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
ECHO ---------------------------------------------->> log.txt
ECHO -----------========================----------->> log.txt
ECHO -----------=========%date%=========----------->> log.txt
ECHO -----------========================----------->> log.txt
ECHO ---------------------------------------------->> log.txt

set DD=0
Set TIMESTAMP="eol=; tokens=1,2,3,4* delims=/, "
For /F %TIMESTAMP% %%i in ('DATE /t') DO (
  SET YYYYMMDD=%%l%%j%%k
  SET YYYYMM=%%l%%j
  set DD=%%k
)

echo A >> ServiceNames
echo B >> ServiceNames
echo C >> ServiceNames
echo D >> ServiceNames
echo E >> ServiceNames
echo F >> ServiceNames

for /f %%a in (ServiceNames) do (
    set timestamp=!date!!time!
    ECHO !timestamp! - Stopping Service %%a >> log.txt
    net stop /y srvService_%%a >> log.txt
    taskkill /f /im Service_%%a.exe >> log.txt

    ping localhost -n 15 > nul

    set timestamp=!date!!time!
    ECHO !timestamp! - Starting Service %%a >> log.txt
    net start srvService_%%a >> log.txt
)
if exist ServiceNames del ServiceNames

The problem is that on a couple of occasions, the batch file won't wait for one service to completely finish starting before stopping the next service.

Do you think adding an additional ping localhost command after the net start command might help?

Best Answer

You can use code like the following to keep waiting till the service (in this case I've tested with w32time) is started:

:WAIT
timeout /t 5 > NUL
for /f "tokens=4" %%s in ('sc query w32time ^| find "STATE"') do if NOT "%%s"=="RUNNING" goto WAIT
echo Service is now running!