起因: 同事写的C# windows 服务太不靠谱了. 老是挂. 给我造成巨大的麻烦 (我是技术支持,擦屁股的)
所以想自己学习写windows 服务并检测他的服务的运行状态,一旦挂掉,能在很短的时间内给他启动起来.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;
namespace TestService
{
public partial class Service1 : ServiceBase
{
string nowtime = System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"); //输出当前时间
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Debug.WriteLine("正在开始检测服务" + " " + nowtime);
System.Timers.Timer t = new System.Timers.Timer(); //定义一个定时器
t.Interval = 20000; //时间间隔为5s
t.Elapsed += new System.Timers.ElapsedEventHandler(Checkstatus); //到点执行事件
t.AutoReset = true; //重复执行
t.Enabled = true;// 是否执行elapsed 事件
}
public void Checkstatus(object source,System.Timers.ElapsedEventArgs e)
{
int intSecond = e.SignalTime.Second;
try
{
ServiceController sc = new ServiceController("TeamViewer9");
Debug.WriteLine("正在检测" +sc.ServiceName+" " + nowtime);
string serviceStutus=sc.Status.ToString();
if (string.Equals(serviceStutus, "Running"))
{
Debug.WriteLine(sc.ServiceName + " " + "服务正在运行" + " "+nowtime);
}
else
{
Debug.WriteLine(sc.ServiceName + " " + "服务不在运行" + " " + nowtime);
writestr(nowtime+sc.ServiceName+" "+"服务停止");
Debug.WriteLine("准备启动服务" + " " + sc.ServiceName + " " + nowtime);
sc.Refresh();
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
}
Thread.Sleep(10000);
}
catch (System.Exception err)
{
writestr(err.Message);
}
}
protected override void OnStop()
{
Debug.WriteLine("正在结束服务" + " "+ nowtime);
}
public void writestr(string readme)
{
StreamWriter dout = new StreamWriter(@"D:\" + "WindowsServiceTestLog.txt", true);
dout.Write("\r\n事件:" + readme + "\r\n操作时间:" + System.DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
dout.Close();
}
}
}
因为是初学,所以里面放了很多debug信息 ,看是否写对了.
拿的是teamview 远程工具的服务来做的测试,效果不错.
另外在生产环境中20S的检测周期是不是太快了,先测试了再说吧.
再说下服务的安装.
1.在解决方案上右键 选择"界面设计器"
2.在界面设计上右键 选择 添加安装程序
3.出现这2个.
4.分别在上面点击右键.选择属性.
Account ---->localsystem 不知道咋解释,如果系统用户1 执行了这个服务,系统用户2 上面同样也有!! 不需要重新安装.
看看就明白了. starttype 就是启动类型, 这个自己随便打开一个系统服务 对照看就是了, 不细说,
5.安装服务.
从系统.net目录下拷贝InstallUtil.exe 这个工具到工程的debug 目录下
在目录下新建1个bat文件 内容为
InstallUtil.exe TestService.exe
即安装生成的服务文件
InstallUtil.exe -u TestService.exe 是删除这个服务.
6. 调试方法
服务安装成功之后,修改代码之后 ,生成解决方案, 先停止测试服务,再开启就OK了.
7. 打印截图
请无视中间 的乱七八糟的打印, 不知道是哪里的....