(转)创建Windows服务(Windows Services)N种方式总结
转自:http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html
最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。
目前我知道的创建创建Windows服务有3种方式:
a.利用.net框架类ServiceBase
b.利用组件Topshelf
c.利用小工具instsrv和srvany
下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志:
a.利用.net框架类ServiceBase
本方式特点:简单,兼容性好
通过继承.net框架类ServiceBase实现
第1步: 新建一个Windows服务

public partial class Service1 : ServiceBase
{
readonly Timer _timer; private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @"\" + "test.txt"; public Service1 ( )
{
InitializeComponent ( ); _timer = new Timer ( 5000 )
{
AutoReset = true ,
Enabled = true
}; _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
{
this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
};
} protected override void OnStart ( string [ ] args )
{
this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
} protected override void OnStop ( )
{
this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
} void witre ( string context )
{
StreamWriter sw = File.AppendText ( FileName );
sw.WriteLine ( context );
sw.Flush ( );
sw.Close ( );
} }

第2步: 添加Installer

[RunInstaller ( true )]
public partial class Installer1 : System.Configuration.Install.Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller; public Installer1 ( )
{
InitializeComponent ( ); processInstaller = new ServiceProcessInstaller ( );
serviceInstaller = new ServiceInstaller ( ); processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "my_WindowsService";
serviceInstaller.Description = "WindowsService_Description";
serviceInstaller.DisplayName = "WindowsService_DisplayName"; Installers.Add ( serviceInstaller );
Installers.Add ( processInstaller );
}
}

第3步:安装,卸载
Cmd命令
installutil WindowsService_test.exe (安装Windows服务)
installutil /u WindowsService_test.exe (卸载Windows服务)
代码下载:http://files.cnblogs.com/aierong/WindowsService_test.rar
b.利用组件Topshelf
本方式特点:代码简单,开源组件,Windows服务可运行多个实例
Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com
第1步:引用程序集TopShelf.dll和log4net.dll
第2步:创建一个服务类MyClass,里面包含两个方法Start和Stop,还包含一个定时器Timer,每隔5秒往文本文件中写入字符

public class MyClass
{
readonly Timer _timer; private static readonly string FileName = Directory.GetCurrentDirectory ( ) + @"\" + "test.txt"; public MyClass ( )
{
_timer = new Timer ( 5000 )
{
AutoReset = true ,
Enabled = true
}; _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
{
this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
};
} void witre ( string context )
{
StreamWriter sw = File.AppendText ( FileName );
sw.WriteLine ( context );
sw.Flush ( );
sw.Close ( );
} public void Start ( )
{
this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
} public void Stop ( )
{
this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
} }

第3步:使用Topshelf宿主我们的服务,主要是Topshelf如何设置我们的服务的配置和启动和停止的时候的方法调用

class Program
{
static void Main ( string [ ] args )
{
HostFactory.Run ( x =>
{
x.Service<MyClass> ( ( s ) =>
{
s.SetServiceName ( "ser" );
s.ConstructUsing ( name => new MyClass ( ) );
s.WhenStarted ( ( t ) => t.Start ( ) );
s.WhenStopped ( ( t ) => t.Stop ( ) );
} ); x.RunAsLocalSystem ( ); //服务的描述
x.SetDescription ( "Topshelf_Description" );
//服务的显示名称
x.SetDisplayName ( "Topshelf_DisplayName" );
//服务名称
x.SetServiceName ( "Topshelf_ServiceName" ); } );
}
}

第4步: cmd命令
ConsoleApp_Topshelf.exe install (安装Windows服务)
ConsoleApp_Topshelf.exe uninstall (卸载Windows服务)
代码下载:http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar
c.利用小工具instsrv和srvany
本方式特点:代码超级简单,WindowsForm程序即可,并支持程序交互(本人最喜欢的特点),好像不支持win7,支持xp win2003
首先介绍2个小工具:
instsrv.exe:用以安装和卸载可执行的服务
srvany.exe:用于将任何EXE程序作为Windows服务运行
这2个工具都是是Microsoft Windows Resource Kits工具集的实用的小工具
你可以通过下载并安装Microsoft Windows Resource Kits获得 http://www.microsoft.com/en-us/download/details.aspx?id=17657
第1步: 新建WindowsForm程序

public partial class Form1 : Form
{
Timer _timer; private static readonly string FileName = Application.StartupPath + @"\" + "test.txt"; public Form1 ( )
{
InitializeComponent ( );
} private void Form1_Load ( object sender , EventArgs e )
{
_timer = new Timer ( )
{
Enabled = true ,
Interval = 5000
}; _timer.Tick += delegate ( object _sender , EventArgs _e )
{
this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
};
} void _timer_Tick ( object sender , EventArgs e )
{
throw new NotImplementedException ( );
} void witre ( string context )
{
StreamWriter sw = File.AppendText ( FileName );
sw.WriteLine ( context );
sw.Flush ( );
sw.Close ( );
} private void button1_Click ( object sender , EventArgs e )
{
MessageBox.Show ( "Hello" );
} }

第2步:安装,卸载
服务的安装步骤分5小步:
(1)打开CMD,输入以下内容,其中WindowsForms_WindowsService为你要创建的服务名称
格式:目录绝对路径\instsrv WindowsForms_WindowsService 目录绝对路径\srvany.exe
例如:
D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService D:\TempWork\win\Debug\srvany.exe
(2)regedit打开注册表编辑器,找到以下目录
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WindowsForms_WindowsService
(3)鼠标右键单击WindowsForms_WindowsService,创建一个"项",名称为"Parameters"
(4)鼠标左键单击"Parameters",在右边点击鼠标右键,创建一个"字符串值"(REG_SZ),名称为"Application",数值数据里填写目录下可执行文件的绝对路径+文件名
例如:
D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe
(5)打开services.msc服务控制面板,找到WindowsForms_WindowsService服务,鼠标右键-属性-登陆,勾选"允许服务与桌面交互"
启动服务,可以看到程序界面
卸载服务
D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService REMOVE
代码下载:http://files.cnblogs.com/aierong/WindowsFormsApplication_Exe.rar
(转)创建Windows服务(Windows Services)N种方式总结的更多相关文章
- 用C#创建Windows服务(Windows Services)
用C#创建Windows服务(Windows Services) 学习: 第一步:创建服务框架 创建一个新的 Windows 服务项目,可以从Visual C# 工程中选取 Windows 服务(W ...
- C# windows服务:创建Windows服务(Windows Services)的一般步骤
C#创建Windows服务(Windows Services) Windows服务在Visual Studio 以前的版本中叫NT服务,在VS.net启用了新的名称.用Visual C# 创建Wind ...
- Python创建进程、线程的两种方式
代码创建进程和线程的两种方式 """ 定心丸:Python创建进程和线程的方式基本都是一致的,包括其中的调用方法等,学会一个 另一个自然也就会了. "" ...
- Linux中设置服务自启动的三种方式
有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务 主要用三种方式进行这一操作: ln -s 在/etc/rc.d/rc*.d目录中建立/e ...
- [转]Linux中设置服务自启动的三种方式
from:http://www.cnblogs.com/nerxious/archive/2013/01/18/2866548.html 有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统 ...
- dubbo服务运行的三种方式
dubbo服务运行,也就是让生产服务的进程一直启动.如果生产者进程挂掉,也就不存在生产者,消费者不能进行消费. Dubbo服务运行的三种方式如下:1.使用Servlet容器运行(Tomcat.Jett ...
- (转)Linux中设置服务自启动的三种方式
有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务 主要用三种方式进行这一操作: ln -s 在/etc/rc.d/rc*.d目录中建立/e ...
- 【转发】Linux中设置服务自启动的三种方式
有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务 主要用三种方式进行这一操作: ln -s 在/etc/rc.d/rc*.d目录中建立/e ...
- iOS:创建单例对象的两种方式
单例模式:创建单例对象的两种方式 方式一:iOS4版本之前 static SingleClassManager *singleManager = nil; +(SingleClas ...
- String常用使用方法,1.创建string的常用3+1种方式,2.引用类型使用==比较地址值,3.String当中获取相关的常用方法,4.字符串的截取方法,5.String转换常用方法,6.切割字符串----java
一个知识点使用一个代码块方便查看 1.创建string的常用3+1种方式 /* 创建string的常用3+1种方式 三种构造方法 public String():创建一个空字符串,不含有任何内容: p ...
随机推荐
- SpringBoot整合elasticsearch
在这一篇文章开始之前,你需要先安装一个ElasticSearch,如果你是mac或者linux可以参考https://www.jianshu.com/p/e47b451375ea,如果是windows ...
- 前缀和的应用 CodeForces - 932B Recursive Queries
题目链接: https://vjudge.net/problem/1377985/origin 题目大意就是要你把一个数字拆开,然后相乘. 要求得数要小于9,否则递归下去. 这里用到一个递归函数: i ...
- JavaScript基础笔记(十)表单脚本
表单脚本 一.表单基础知识 JavaScript中表单对应的是HTMLFormElement类型,该类型继承自HTMLElement类型. 通过document.forms可以获得所有表单元素,通过数 ...
- php 将时间格式 转为时间戳
<?php $gte = "2018-08-08"; $year=((int)substr($gte,0,4));//取得年份: $month=((int)substr($g ...
- [CF1038D]Slime
[CF1038D]Slime 题目大意: 有\(n(n\le5\times10^5)\)只史莱姆,每只史莱姆有一个分数\(w_i(|w_i|le10^9)\),每次一只史莱姆可以吞掉左边的或者右边的史 ...
- BZOJ4966 : 总统选举
线段树维护每个点的最有可能是答案的数以及它的权重. 合并两个节点的时候,将权重互相抵消,保留较大的那一个. 得到答案后,再在对应权值的Treap中查询出现次数,检查是否真正是答案. 时间复杂度$O(n ...
- [POJ]代码托运站
这里暂时是空的
- 考前停课集训 Day1 废
[友情链接] Day1 今天模拟赛倒数…… 感觉自己菜到爆炸…… 被一个以前初一的倒数爆踩…… 感觉自己白学了. 满分400,自己只有100.真的是倒数第一…… 做了一个T2,其他暴力分全部没有拿到… ...
- 部署wepy框架开发微信小程序
我用的是yarn,如果你使用的是npm,也可以 首先需要安装wepy命令行工具 npm install wepy-cli -g 然后在选定的位置使用脚手架工具创建wepy项目 wepy init st ...
- JS 引用类型之Object
引用类型定义: 描述一类对象具有的属性和方法 引用类型Object ,也就是我们常说的对象类型了,这应该是JavaScript中最常见的引用类型了. 对象是某个引用类型的实例,如何创建一个实例,也就是 ...