Topshelf:一款非常好用的 Windows 服务开发框架 转发https://www.cnblogs.com/happyframework/p/3601995.html

背景

多数系统都会涉及到“后台服务”的开发,一般是为了调度一些自动执行的任务或从队列中消费一些消息,开发 windows service 有一点不爽的是:调试麻烦,当然你还需要知道 windows service 相关的一些开发知识(也不难),本文介绍一个框架,让你让 console application 封装为 windows service,这样你就非常方便的开发和调试 windows service。

TopShelf

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Timers;
 7 
 8 using Topshelf;
 9 using Topshelf.Builders;
10 using Topshelf.Configurators;
11 using Topshelf.HostConfigurators;
12 
13 namespace TopshelfStudy
14 {
15     public sealed class TimeReporter
16     {
17         private readonly Timer _timer;
18         public TimeReporter()
19         {
20             _timer = new Timer(1000) { AutoReset = true };
21             _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("当前时间:{0}", DateTime.Now);
22         }
23         public void Start() { _timer.Start(); }
24         public void Stop() { _timer.Stop(); }
25     }
26 
27     class Program
28     {
29         static void Main(string[] args)
30         {
31             HostFactory.Run(x =>
32             {
33                 x.Service<TimeReporter>(s =>
34                 {
35                     s.ConstructUsing(settings => new TimeReporter());
36                     s.WhenStarted(tr => tr.Start());
37                     s.WhenStopped(tr => tr.Stop());
38                 });
39 
40                 x.RunAsLocalSystem();
41 
42                 x.SetDescription("定时报告时间");
43                 x.SetDisplayName("时间报告器");
44                 x.SetServiceName("TimeReporter");
45             });
46         }
47     }
48 }
复制代码

备注

TopShelf 提高的 API 非常简单,也提高了和 Log4Net 的集成,结合 Quartz(后面介绍),可以实现任务调度服务。

posted @ 2019-04-28 16:48  DarJeely  阅读(274)  评论(0编辑  收藏  举报