Blog maintained by TechnoGems

Friday, October 9, 2009

How to create your own Windows Service Monitor? - A scheduled task

There are times when a windows service just stops running without any error. The following script provides a brute force script that will help monitor the service and restart it if the service is down.

To create this service, copy the following code to a cmd file and setup a schedule task. (Replace YourServiceName with the actual name of your service)


@ECHO OFF
set logFile=c:\temp\svcmonitor.log
set tempFile=c:\temp\tmp.txt
set serviceName=YourServiceName
sc query %serviceName% > %tempFile%
for /F "skip=3 tokens=1,4" %%i in (%tempFile%) do if %%i equ STATE (
if %%j equ STOPPED (
echo %date% %time% %serviceName% service is stopped. Trying to restart. >> %logFile%
sc start %serviceName% >> %logFile%
echo %date% %time% %serviceName% restarted >> %logFile%
) else (
echo %date% %time% %serviceName% service is %%j >> %logFile%
)
)


Now update the scheduled task in to run every day. Then go to the advanced scheduling options menu and set to repeat the task every 10 minutes(or what ever frequency deemed appropriate for your task) as shown below. Now you have a poor man's version of a windows service monitor.

No comments: