摘要

很多情况下,都会使用windows服务做一些任务,但总会有一些异常,导致服务停止。这个时候,开发人员又不能立马解决问题,所以做一个守护者服务还是很有必要的。当检测到服务停止了,重启一下服务,等开发人员到位了,再排查错误日志。

代码

app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<!--要守护的服务的服务名称-->
<add key="toWatchServiceName" value=""/>
<!--守护服务的名称-->
<add key="serviceName" value="邮件提醒服务守护服务"/>
<!--每1分钟检查一次 以秒为单位-->
<add key="timerInterval" value=""/>
</appSettings>
</configuration>

服务

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; namespace WindowsService.Watch
{
partial class ServiceWather : ServiceBase
{
private static string currentExePath = string.Empty;
public ServiceWather()
{
InitializeComponent();
currentExePath = AppDomain.CurrentDomain.BaseDirectory;
}
/// <summary>
/// 检查间隔
/// </summary>
private static readonly int _timerInterval = Convert.ToInt32(ConfigurationManager.AppSettings["timerInterval"]) * ;
/// <summary>
/// 要守护的服务名
/// </summary>
private static readonly string toWatchServiceName = ConfigurationManager.AppSettings["toWatchServiceName"];
private System.Timers.Timer _timer;
protected override void OnStart(string[] args)
{
//服务启动时开启定时器
_timer = new System.Timers.Timer();
_timer.Interval = _timerInterval;
_timer.Enabled = true;
_timer.AutoReset = true;
_timer.Elapsed += _timer_Elapsed;
LogHelper.WriteLog(currentExePath, "守护服务开启");
} void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//如果服务状态为停止,则重新启动服务
if (!CheckSericeStart(toWatchServiceName))
{
StartService(toWatchServiceName);
}
} protected override void OnStop()
{
if (_timer != null)
{
_timer.Stop();
_timer.Dispose();
LogHelper.WriteLog(currentExePath, "守护服务停止");
}
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">要启动的服务名称</param>
private void StartService(string serviceName)
{
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName.Trim() == serviceName.Trim())
{
service.Start();
//直到服务启动
service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(, , ));
LogHelper.WriteLog(currentExePath, string.Format("启动服务:{0}", serviceName));
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog(currentExePath, ex);
}
}
private bool CheckSericeStart(string serviceName)
{
bool result = true;
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName.Trim() == serviceName.Trim())
{
if ((service.Status == ServiceControllerStatus.Stopped)
|| (service.Status == ServiceControllerStatus.StopPending))
{
result = false;
}
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog(currentExePath, ex);
}
return result;
}
/// <summary>
/// 停止
/// </summary>
/// <param name="serviceName"></param>
private void StopService(string serviceName)
{
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName.Trim() == serviceName.Trim())
{
service.Stop();
//直到服务停止
service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(, , ));
LogHelper.WriteLog(currentExePath, string.Format("启动服务:{0}", serviceName));
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog(currentExePath, ex);
}
}
}
}

[C#]通用守护进程服务的更多相关文章

  1. 在C#/.NET应用程序开发中创建一个基于Topshelf的应用程序守护进程(服务)

    本文首发于:码友网--一个专注.NET/.NET Core开发的编程爱好者社区. 文章目录 C#/.NET基于Topshelf创建Windows服务的系列文章目录: C#/.NET基于Topshelf ...

  2. 用C#实现通用守护进程

    1. 下载 源码下载:http://pan.baidu.com/s/1vqDA2 安装包下载:http://pan.baidu.com/s/1sjmEB0p 2. 安装注意事项 在配置档中配置你要守护 ...

  3. 创建Android守护进程(底层服务)【转】

    本文转载自:https://blog.csdn.net/myfriend0/article/details/80016739 创建Android守护进程(底层服务) 前言 Android底层服务,即运 ...

  4. Linux_控制服务与守护进程

    一.systemd 1.systemd简介 1️⃣:systemd是用户空间的第一个应用程序,即/sbin/init 2️⃣:init程序的类型: SysV风格:init(centos5),实现系统初 ...

  5. 守护进程与Supervisor

    博客链接:http://www.cnblogs.com/zhenghongxin/p/8676565.html 消息队列处理后台任务带来的问题 在系统稍微大些的时候,我们经常会用到消息队列(实现的方式 ...

  6. shell脚本(管理守护进程)

    工作中常常会遇到处理消息队列的消费者进程,这样的进程是一个守护进程,即一个服务.服务通常写个shell脚本来管理,查询服务的status  ,启动start 关闭stop  重启reload.最近在学 ...

  7. CentOS7 安装supervisor守护进程管理器

    supervisor没有发布在标准的CentOS源在,需要安装epel源.这种方式安装的可能不是最新版本,但比较方便,安装完成之后,配置文件会自动帮你生成. 默认配置文件:/etc/superviso ...

  8. asp.net core2.0 部署centos7/linux系统 --守护进程supervisor(二)

    原文:asp.net core2.0 部署centos7/linux系统 --守护进程supervisor(二) 续上一篇文章:asp.net core2.0 部署centos7/linux系统 -- ...

  9. supervisord守护进程的使用

    原文链接:http://blog.csdn.net/xyang81/article/details/51555473 Supervisor(http://supervisord.org/)是用Pyth ...

随机推荐

  1. Using the rJava package on Win7 64 bit with R

    加载 rJava 包报错: > library(rJava) Error : loadNamespace()里算'rJava'时.onLoad失败了,详细内容: 调用: fun(libname, ...

  2. Debugger 怎么用

    Debugger 是一个很有用的工具,尤其对于workflow开发人员来说.可以帮助我们check 从source 到target的数据流.我们可以看到什么数据从source中流出,在接下来的tran ...

  3. 【BZOJ-1597】土地购买 DP + 斜率优化

    1597: [Usaco2008 Mar]土地购买 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 2931  Solved: 1091[Submit] ...

  4. cookielib和urllib2模块相结合模拟网站登录

    1.cookielib模块 cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源.例如可以利用 本模块的CookieJar类的对 ...

  5. 执行查询报: Incorrect key file for table ‘test’; try to repair it

    报错信息如下:程序没有错误,但执行会报错,错误定在执行语句上 查了一下资料 网上的解决办法,亲试可用: mysql> use news;Database changedmysql> rep ...

  6. Some Simple Models of Neurons

    Linear neuron: \[y=b+\sum\limits_i{x_i w_i}\] Binary threshold neuron: \[z = \sum\limits_i{x_i w_i}\ ...

  7. 常见linux命令释义(第三天)

    今天晚上看鸟哥的私房菜,边学边写笔记. 在linux中压缩大多是.tar, .tar.gz , .tgz, /gz, .bz2等. .gz 是通过gzip压缩的文件. .bz2 是通过bzip2压缩的 ...

  8. 我总结的js性能优化的小知识

    前言 一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对javascript理解的还不够透彻异或是自己太笨,更多的是自己 ...

  9. NOIp 0910 爆零记

    这套题是神犇chty出的. 刚拿到题的时候有点懵逼,因为按照一般的套路第一题都是一眼题,但是看到第一题后想了很多个算法和数据结构好像都不能很好的解决.然后就随手敲了个暴力去看T2. 嗯...文件名是b ...

  10. JS-DOM2级封装练习题--点击登录弹出登录对话框

    <!doctype html><html lang="en"> <head> <meta charset="UTF-8" ...