[英]Email me if windows service stops
我希望能够检查某个服务是否正在运行(假设它有一个显示名称 - ServiceA)。 我希望我的程序检查说服务仍然运行每5分钟。 如果没问题,它将循环并再等5分钟,然后再次检查。 如果发现ServiceA已停止,我希望程序给我发电子邮件并说... ServiceA已停止运行。 下面我有我到目前为止所做的代码,它能够将所有当前服务运行并将实际显示名称返回到控制台。 任何关于上面我需要的代码/逻辑的想法?
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();
}
}
}
将每个服务的名称放在一个数组中,检查您想要的名称是否正在运行
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
}
如果您知道要查找哪个服务,则无需迭代所有服务:您可以使用服务名称实例化ServiceController
。
至于发送电子邮件:看一下System.Net.Mail.MailMessage类。
注意:您知道您也可以将服务配置为在失败时触发操作吗?
您需要跟踪需要某种存储的服务状态。 最简单的可能是跟踪服务状态的XML文件,也许是这样的模式
<services>
<service name="service1" last-check="12/21/2011 13:00:05" last-status="running" />
...
</services>
您的监控应用程序将唤醒,查找其感兴趣的服务的状态,并检查该服务的先前状态。 如果状态正在运行,但当前已停止,请发送电子邮件。 如果未找到该服务,请将其添加到服务列表中。
当监控应用程序出现故障时,将服务状态保持为磁盘可以保护您。
下面是一个服务的例子,它做了类似的事情。 应该简单地适应您的需求..
public partial class CrowdCodeService : ServiceBase
{
private Timer stateTimer;
private TimerCallback timerDelegate;
AutoResetEvent autoEvent = new AutoResetEvent(false);
public CrowdCodeService()
{
InitializeComponent();
}
int secondsDefault = 30;
int secondsIncrementError = 30;
int secondesMaximum = 600;
int seconds;
protected override void OnStart(string[] args)
{
Loggy.Add("Starting CrowdCodeService.");
timerDelegate = new TimerCallback(DoSomething);
seconds = secondsDefault;
stateTimer = new Timer(timerDelegate, autoEvent, 0, seconds * 1000);
}
static bool isRunning = false;
// The state object is necessary for a TimerCallback.
public void DoSomething(object stateObject)
{
if (CrowdCodeService.isRunning)
{
return;
}
CrowdCodeService.isRunning = true;
AutoResetEvent autoEvent = (AutoResetEvent)stateObject;
try
{
////// Do your work here
string cs = "Application";
EventLog elog = new EventLog();
if (!EventLog.SourceExists(cs))
{
EventLog.CreateEventSource(cs, cs);
}
elog.Source = cs;
elog.EnableRaisingEvents = true;
elog.WriteEntry("CrowdCodes Service Error:" + cmd.Message.ToString(), EventLogEntryType.Error, 991);
}
}
finally
{
CrowdCodeService.isRunning = false;
}
}
protected override void OnStop()
{
Loggy.Add("Stopped CrowdCodeService.");
stateTimer.Dispose();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.