Scheduled Task to Ensure that a Windows Service is Running

Windows Server logo

Some applications running under Windows services do not always remain in the running state, even when there is no apparent reason that they should stop. This is often due to a bug in the application, or perhaps the connection with the database that was being used by the application was temporarily broken.

In my case, a third-party application that I support (with no control over its source code) has a service that stops without warning to the user from time to time. Regardless of the reason as to why the stop control was sent by the application, the service needs to be running all the time. If this service were stopping due to a crash in the service, Windows has options in the services dialog box that can automatically restart a crashed service, or restart the server itself. These options do not help me, as it is the application sending a stop command to the service. I needed a simple way to ensure that the service is always running. The following batch file, using the actual Service Name (not the Display Name) of the service in place of “ServiceName”, will start the service if it is not running, and do nothing otherwise.

@ECHO OFF
FOR /F "tokens=3 delims=: " %%H IN ('SC QUERY "ServiceName" ^| FINDSTR "        STATE"') DO (
  IF /I "%%H" NEQ "RUNNING" (
   NET START "ServiceName"
  )
)

By saving this as a batch file and setting up a Scheduled Task to run the file on a regular interval such as every five or ten minutes, this will minimize the necessity of manually restarting the service when it is shut down unintentionally, that is, without the intention of the application administrator. The task should be disabled when one needs to have the service shut down for maintenance or troubleshooting.