Cristi Manole
Cristi Manole

Reputation: 31

Keep running batch loop after starting .exe

My program.exe sometimes stops. I have made batch script that checks if program is running and start it if not in loop.

The problem is loop is exiting after program.exe is started and runned.

I need to keep running the loop to keep checking every 5 mins if program still running or needs to be started again.

set loopcount=10000
:loop

tasklist /FI "IMAGENAME eq program.exe" /FO CSV > search.log

FINDSTR program.exe search.log > found.log

FOR /F %%A IN (found.log) DO IF %%~zA EQU 0 GOTO end

echo Starting..
start /b C:\_Program\program.exe

:end

del search.log
del found.log

echo Waiting..
timeout /t 300 /nobreak


if %loopcount%==0 goto exitloop
goto loop
:exitloop
pause

Upvotes: 0

Views: 606

Answers (3)

Eric Eskildsen
Eric Eskildsen

Reputation: 4759

Batch File

If you have to use a batch file, I'd suggest:

  1. Removing the loop
  2. Running it every 5 minutes using a scheduled task

A scheduled task is more robust than an infinite loop in case the process crashes.

Run this once to schedule a task that repeats every 5 minutes:

schtasks /CREATE /SC DAILY /MO 1 /TN 'Name To Give the Scheduled Task' /TR 'C:\path\to\your\script.bat' /ST 0:00 /RI 5 /DU 24:00

PowerShell

If you can use PowerShell, the equivalent is a bit simpler:

if ($null -eq (ps program -ErrorAction SilentlyContinue)) {
    saps C:\_Program\program.exe
}

Run this once to schedule a task that repeats every 5 minutes:

schtasks /CREATE /SC DAILY /MO 1 /TN 'Name To Give the Scheduled Task' /TR 'powershell -EB C:\path\to\your\script.ps1' /ST 0:00 /RI 5 /DU 24:00

Upvotes: 1

user7818749
user7818749

Reputation:

It might be as simple as:

@echo off
:repeat
tasklist | findstr /i "program.exe">nul
if not %errorlevel% equ 0 start /b "C:\_Program\program.exe"
timeout /t 10 /nobreak>nul && goto :repeat

This does tasklist and we use findstr to determine errorlevel if not 0 start program, timeout for 10 seconds and repeat, no external files needed.

Upvotes: 1

Hackoo
Hackoo

Reputation: 18827

Here is an example to test. To achieve continuously check (in loop) the existence of process "WinRAR.exe" (as an example of application to check); so you can change of course the path and the process name to check.

@echo off
Set "MyApplication=%Programfiles%\WinRAR\WinRAR.exe"
Set "MyProcess=WinRAR.exe"
Color 9B
Title Check Running process "%MyProcess%"
mode con cols=75 lines=2
:Loop
cls
tasklist /nh /fi "imagename eq %MyProcess%" 2>nul |find /i "%MyProcess%" >nul
If not errorlevel 1 (Echo "%MyProcess%" is running) else (start "" "%MyApplication%")
ping -n 60 127.0.0.1 >nul 
goto Loop

Upvotes: 0

Related Questions