In a distant past (circa 2011), I had a situation where it was necessary to watchdog a Windows service.
So, I created a VB.NET project of the type console that could be executed on .NET 4.0.
At the time, we decided the watchdog would need to send an email in case the service (usually a Tomcat instance) was found down and that it would try to restart Tomcat in such cases.
So, the following fields were used:
Imports System
Imports System.Net
Imports System.Net.Mail
Imports System.ServiceProcess
Module Main
Sub Main()
While (True)
Call CheckService()
System.Threading.Thread.Sleep(My.Settings.sleeptime)
End While
End Sub
Public Sub SendEmail()
Dim Message As New Net.Mail.MailMessage()
Dim FromEmail As New Net.Mail.MailAddress(My.Settings.email.from)
Message.From = FromEmail
Message.To.Add(My.Settings.email.to)
Message.Subject = My.Settings.email.title
Message.Body = My.Settings.email.content
Message.Priority = Net.Mail.MailPriority.High
'587 for gmail, 25 for most...
Dim SmtpClient As New Net.Mail.SmtpClient(My.Settings.smtp.server,
My.Settings.smtp.port)
SmtpClient.Send(Message)
End Sub
Private Sub CheckService()
Dim Service As ServiceController
Dim Services As ServiceController() = ServiceController.GetServices()
Try
For Each Service In Services
'service statuses: ContinuePending, Paused, PausePending, Running, StartPending, Stopped, StopPending
'Console.WriteLine("service: " + Service.ServiceName.ToString + " status: " + Service.Status.ToString)
If Service.ServiceName.StartsWith(My.Settings.service.Name)
And (Service.Status.ToString.StartsWith("Stopped")
Or Service.Status.ToString.StartsWith("Paused")
Or Service.Status.ToString.StartsWith("StopPending")
Or Service.Status.ToString.StartsWith("PausePending")) Then
SendEmail()
Service.Start()
Exit Try
End If
Next Service
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module