.net手动编写Windows服务
1,打开VS,新建一个windows服务程序。项目名称自定义,我这里用的默认名称:Service1

2,打开Service1,按F7查看代码。代码里有三个方法:public Service1()、protected override void OnStart(string[] args)、protected override void OnStop(),
分别是构造函数,服务启动方法,服务停止方法
3,定义一个timer定时器,设置一段时间自动执行:
System.Timers.Timer timer1; //计时器
timer1 = new System.Timers.Timer();
timer1.Interval = 3000; //设置计时器事件间隔执行时间
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
timer1.Enabled = true;
4,编写服务具体执行的业务,这里是模拟的,就只写了一个txt文档,并且把写txt文档的方法放到了定时器的自动执行方法里
/// <summary>
/// 执行的事件
/// </summary>
/// <param name="obj"></param>
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",自动服务的执行。。。");
}
}
5,编译一下,无编译错误即可。完整的代码如下:
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer1; //计时器
string filePath = @"D:\MyServiceLog.txt";
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1 = new System.Timers.Timer();
timer1.Interval = 3000; //设置计时器事件间隔执行时间
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
timer1.Enabled = true;
using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",服务启动!");
}
}
protected override void OnStop()
{
this.timer1.Enabled = false;
using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",服务停止!");
}
}
/// <summary>
/// 执行的事件
/// </summary>
/// <param name="obj"></param>
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",自动服务的执行。。。");
}
}
}
6,在解决方案里双击Service.cs,打开设计器:


在空白处右击,选择“添加安装程序”

点击之后如下

7,查看serviceInstaller1的属性,编辑它的描述信息和服务名称信息,如下:

点击 serviceProcessInstaller1 ,编辑运行次服务的账户类型属性,设置成 LocalSystem,如下:

8,服务配置完成,点击保存,重新生成。
9,下面,我们写一个Windows窗体,用于安装、运行、停止、卸载这个服务:

10,添加一个应用引用,把刚才写的服务引用到这个Windows窗体应用

11,给每个按钮添加相应的代码,完整如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string serviceFilePath = System.Environment.CurrentDirectory + "\\WindowsService1.exe";
string serviceName = "TestWindowsService";
/// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.UninstallService(serviceName);
this.InstallService(serviceFilePath);
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.ServiceStart(serviceName);
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.ServiceStop(serviceName);
}
/// <summary>
/// 卸载服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStop(serviceName);
this.UninstallService(serviceFilePath);
}
}
//判断服务是否存在
private bool IsServiceExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
}
//安装服务
private void InstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
}
}
//卸载服务
private void UninstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
installer.Uninstall(null);
}
}
//启动服务
private void ServiceStart(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();
}
}
}
//停止服务
private void ServiceStop(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
}
}
}
}
12,编译,运行起来,点击安装服务。然后在计算机管理里,查看所有的服务,就可以找到刚才写的服务了:

.net手动编写Windows服务的更多相关文章
- python实现编写windows服务
使用python编写windows服务 最近测试服务器上经常发生磁盘空间不足,每次手动清除比较麻烦,所以写个windows服务定时清理下.中间也遇到过几个坑,一起记录下来. 1.python实现win ...
- C#编写windows服务
项目要求: 数据库用有一张表,存放待下载文件的地址,服务需要轮训表将未下载的文件下载下来. 表结构如下: 过程: VS--文件-->新建项目-->windows-->windows服 ...
- 使用C语言编写windows服务一般框架
原文:使用C语言编写windows服务一般框架 编写windows服务和编写windows应用程序一样,有一些回调函数必须填写且向windows 服务管理器(service manager)进行注册, ...
- C#编写Windows 服务
C#编写Windows 服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时 ...
- C# 编写windows服务及服务的安装、启动、删除、定时执行任务
一.编写windows服务 1.VS2017 - 创建服务Myservice 2.创建好项目之后 --- >> 双击 Service1.cs ---- >> 出现一个设计 ...
- c# 编写windows 服务,并制作安装包
对服务的认识有很多个阶段. 第一阶段:当时还在用c++,知道在一个进程里while(True){},然后里面做很多很多事情,这就叫做服务了,界面可能当时还用Console控制台程序. 第二阶段:知道了 ...
- 手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载
Windows服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动, ...
- 第八篇--编写Windows服务
编写service服务参考网址:https://blog.csdn.net/nodeathphoenix/article/details/24181509 vc获得显示器状态(捕获息屏.亮屏网址):h ...
- 编写Windows服务疑问1:操作过程
Windows 服务开发平时不太受人关注,毕竟那是高大上的项目类型,平常需求也用不上,很多老掉牙的家伙也只知有WinForm,仍不知有WPF,更别说Windows 服务了,正如陶渊明所写的,“不知有汉 ...
随机推荐
- C程序设计-----第2次作业
作业要求一 (15分) 完成下列编程题目,每次上完课都会增加2-3道题目,并将编程过程记录在博客里,一次PTA作业任选一道题目给出设计思路.流程图.源代码和错误记录,其他题目可只给出设计思路.源代码和 ...
- QLoo graphql engine 学习二 基本试用(kubernetes)
已经测试过docker&& docker-compose 的运行模式,下面测试下kubernetes的运行模式 kubernetes 我使用docker for mac qloo 安装 ...
- 写时复制和fork,vfork,clone
写时复制 原理: 用了“引用计数”,会有一个变量用于保存引用的数量.当第一个类构造时,string的构造函数会根据传入的参数从堆上分配内存,当有其它类需要这块内存时,这个计数为自动累加,当有类析构时, ...
- iPhone应用提交流程:如何将App程序发布到App Store
http://www.techolics.com/apple/20120401_197.html 对于刚加入iOS应用开发行列的开发者来说,终于经过艰苦的Coding后完成了第一个应用后最重要的历史时 ...
- php的静态变量的实现
1.静态变量的结构 php脚本编译之后会生成执行opcode组成的opcode_array,执行每个zend_op_array都会生成一个单独的zend_execute_data结构. php的局部变 ...
- Redis队列——PHP操作简单示例
入队操作 <?php $redis = new Redis(); $redis->connect('127.0.0.1',6379); while(True){ try{ $value = ...
- 黄聪:360浏览器、chrome开发扩展插件教程(2)为html添加行为
转载:http://www.cnblogs.com/walkingp/archive/2011/04/02/2002668.html 上一节我们已经讲了Chrome扩展的基础知识,并构建了基础的htm ...
- NGINX 添加MP4、FLV视频支持模块
由于公司网站需要放置视频,但是默认的服务器环境是没有编译这个支持的模块,视频文件只能缓冲完了在播放,非常麻烦. 之前呢也安装了一个nginx_mod_h264_streaming来支持,效果很不错 ...
- Python中常见的数据类型总结
Python提供多种数据类型来存放数据项集合,主要包括序列(列表list和元组tuple),映射(如字典dict),集合(set),下面对这几种一一介绍: 一 序列 1.列表list 列表是一种有序的 ...
- cesium初始化参数
var viewer = new Cesium.Viewer('cesiumContainer',{ animation:false, //动画控制不显示 //baseLayerPicker:fals ...