文章原地址:http://www.80iter.com/blog/1451523192435464
Topshelf 创建.net服务整理和安装步骤
windowsService和topshelf服务区别请看 → windowsSevice程序和topshelf程序创建服务对比
Topshelf下载地址https://github.com/Topshelf/Topshelf/downloads
官网http://topshelf-project.com/
文档http://docs.topshelf-project.com/en/latest/
1、创建项目
2、添加Topshelf,使用nuget安装最新的topshelf程序包
3、编写测试代码,直接贴Program类代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
using System.Timers;
using Topshelf;
namespace TopShelfConsoleApplication
{ public class TownCrier
{
TopshelfClass topshelfClass = new TopshelfClass();
readonly Timer _timer;
public TownCrier()
{
//设定了一个 1000 毫秒的服务执行间隔
_timer = new Timer(1000) { AutoReset = true };
_timer.Elapsed += new ElapsedEventHandler(topshelfClass.Test);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
public class Program
{
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name => new TownCrier());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription( "Topshlef服务描述......" );
x.SetDisplayName( "TopshlefTest" );
x.SetServiceName( "TopshlefTest" );
});
}
}
} |
TopshelfClass处理类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using System;
using System.IO;
using System.Timers;
namespace TopShelfConsoleApplication
{ public class TopshelfClass
{
public void Test( object source, ElapsedEventArgs e)
{
string path = "F:\\TopshelfTest\\TopshelfTest.txt" ;
FileStream fs = new FileStream(path, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now.ToString());
sw.Close();
fs.Close();
}
}
} |
具体说明请参照官网给的技术解释文档,我就不在这里解释代码咯:https://topshelf.readthedocs.org/en/latest/configuration/quickstart.html
我只说明一点:上面代码设置为1秒执行一次,在txt文件追加下时间戳,为了防止本地开发测试的调试问题,可以设置属性:
4、发布部署
a、发布部署包,自行处理
b、进入cmd命令,进入部署包目录,找到exe文件执行install安装命令,如下图:
c、查看本机服务,可见已经安装成功:
d、安装n个相同服务使用命令:-instance " test1" install
e、常用命令
1
2
3
4
5
|
install :ConsoleApplication1.exe install
start:ConsoleApplication1.exe start ,执行后服务被启动 stop:ConsoleApplication1.exe stop ,执行后服务被停止 uninstall:ConsoleApplication1.exe uninstall,执行后服务被卸载 -instance: ConsoleApplication1.exe -instance " test1" install
|
5、测试服务运行,开启两个服务,结果如下:
至此,简单的topshelf服务使用就完成咯~~~~~