摘要

很多情况下,都会使用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. VirtualBox提示:错误,创建一个新任务失败,被召者解决办法

    被召者 RC: REGDB_E_CLASSNOTREG (0x80040154) 目前有两种解决办法: 解决方法一: 打开命令窗口(快捷键:窗口键+R,输入cmd点击确定) 输入cd D:\Progr ...

  2. awk 匹配不是 pattern 的内容

    awk '/pattern/ {next} {print $0}' filename

  3. AS技巧合集「调试技巧篇」

    转载:http://www.apkbus.com/forum.php?mod=viewthread&tid=254726&extra=page%3D2%26filter%3Dautho ...

  4. BZOJ 3173: [Tjoi2013]最长上升子序列

    3173: [Tjoi2013]最长上升子序列 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 1524  Solved: 797[Submit][St ...

  5. [学习笔记]tarjan求割点

    都口胡了求割边,就顺便口胡求割点好了QAQ 的定义同求有向图强连通分量. 枚举当前点的所有邻接点: 1.如果某个邻接点未被访问过,则访问,并在回溯后更新 2.如果某个邻接点已被访问过,则更新 对于当前 ...

  6. Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)

    在windows下使用python时,比如编译python的一个包,会遇到这个问题: error: Microsoft Visual C++ 9.0 is required (Unable to fi ...

  7. sql查找最后一个字符匹配

    DECLARE @str AS VARCHAR(25)='123_234_567' select substring(@str,1,LEN(@str)-CHARINDEX('_',reverse(@s ...

  8. python之简单POST模拟登录

    宿舍自从换了校园网的认证系统就不再用客户端了,只能在网页登录.每次上网都要打开浏览器的话很不方便,而且我有时在ubuntu控制台上想联网但终端文本浏览器似乎不支持页面跳转,既然如此,何不写个客户端呢? ...

  9. bestcoder杯回顾

    题目列表:hdu5214~5223 5214: 当时第一反应是由递推公式推出通项公式,事实证明这就是作!大!死! 因为通项公式是这样的:L[n]=a^(n-1)*(b+L[1])-b 于是就需要快速幂 ...

  10. POJ3735 矩阵

    题意:有n只猫咪,开始时每只猫咪有花生0颗,现有一组操作,由下面三个中的k个操作组成:        1. g i 给i只猫咪一颗花生米        2. e i 让第i只猫咪吃掉它拥有的所有花生米 ...