Auto-restart an executable after the application crashes
One solution is to use a batch file with an infinite for
loop to automatically restart the application if it closes. There are two possibilities here, depending on how the application is designed.
If the application is launched and runs in the same process, you can use a very simple batch file:
@echo off
:Start
C:\path\to\application.exe
:: Wait 30 seconds before restarting.
TIMEOUT /T 30
GOTO:Start
This will run infinitely. Any time application.exe
is closed or crashes, the batch file will restart it.
This will not work if application.exe
launches subapp.exe
and then application.exe
closes. In this case, you would need something more complicated.
@ECHO off
SET _PollingInterval=30
:BatchStart
C:\path\to\application.exe
:Start
:: Uncomment the following line on versions of Windows prior to Windows 7 and comment out the TIMEOUT line. The PING solution will not be 100% accurate with _PolingInterval.
:: PING 127.0.0.1 -n %_PollingInterval% >nul
TIMEOUT /T %_PollingInterval%
SET PID=
FOR /F "tokens=2 delims= " %%i IN ('TASKLIST ^| FIND /i "subapp.exe"') DO SET PID=%%i
IF [%PID%]==[] (
ECHO Application was not running. Restarting script.
GOTO BatchStart
)
GOTO Start
GOTO:EOF
If your application could have various processes, then you can probably use something like FINDSTR /i "subapp.exe application.exe"
instead of FIND /i "subapp.exe"
, but this wouldn't work for processes with spaces in their name as FINDSTR
uses the space as a deliminator.
In order to stop these batch files once they've been started, leave the application open and switch to the command prompt. Then use Ctrl + C and acknowledge you want to end the script. Once the script is terminated, close the application.
Further reading:
-
Timeout - Add a delay, also mentions
PING
- Find - Search for text
-
FindStr - Search for text (more complex than
FIND
) - Tasklist - Display all running applications and services
-
Escape Characters, Delimiters and Quotes - The
^
character in the for loop is an escape character
Related videos on Youtube
Bachalo
Updated on September 18, 2022Comments
-
Bachalo almost 2 years
I'm creating a standalone application for a kiosk that must be up and running 24 7.
In the rare event the application crashes, I need some way to make it auto-restart. I'm running Windows 10 on a Nuc.
Can any Windows experts suggest the best way to achieve this?
-
LPChip almost 6 yearsAnother option could be to create a service of the application. A service can be set to restart itself 3 times. This will eliminate a command prompt window being shown that can be closed by anyone. This is harder to setup though...
-
-
Bachalo almost 6 yearsThanks! One quick question, how would I add a delay to the simplest (1st) solution so the application wouldn't restart immediately?
-
Worthwelle almost 6 yearsYou can use the
TIMEOUT
command. I've added it to the example in the answer.