Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email me if windows service stops

I want to be able to check if a certain service is running (say it had a Display name - ServiceA). I want my program to check say every 5 mins that the service is still running. If it is fine, it will loop and wait another 5 mins and then check again. If it finds that ServiceA has stopped I want the program to email me and say...ServiceA has stopped running. Below I have the code which I have done so far which is able to pull all the current services running and there actual display name back to the console. Anyone any ideas on the code/logic needed for what I need above?

namespace ServicesChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceController[] scServices;
            scServices = ServiceController.GetServices();

            Console.WriteLine("Services running on the local computer:");
            foreach (ServiceController scTemp in scServices)
            {
                if (scTemp.Status == ServiceControllerStatus.Running)
                {
                    Console.WriteLine();
                    Console.WriteLine("  Service :        {0}", scTemp.ServiceName);
                    Console.WriteLine("    Display name:    {0}", scTemp.DisplayName); 
                }
            }
            //Create a Pause....
            Console.ReadLine();
        }
    }
}
like image 202
Ctrl_Alt_Defeat Avatar asked Jan 22 '26 01:01

Ctrl_Alt_Defeat


2 Answers

Put every service's name in an array and check if your wanted name is running

List<string> arr = new List<string>();    
foreach (ServiceController scTemp in scServices)
{
    if (scTemp.Status == ServiceControllerStatus.Running)
    {
        arr.add(scTemp.ServiceName);
    }
}
if (arr.Contains("YourWantedName")
{
    // loop again
}
else
{
    // send mail
}
like image 68
Moonlight Avatar answered Jan 24 '26 14:01

Moonlight


There's no need to iterate over all services, if you know which one you're looking for: you can instantiate ServiceController with the service name.

As for sending an email: take a look at the System.Net.Mail.MailMessage class.

NB: You know that you can also just configure the service to trigger an action if it fails?

like image 35
Arnout Avatar answered Jan 24 '26 14:01

Arnout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!