zoukankan      html  css  js  c++  java
  • 使用TopShelf轻松开发Window服务

    关于TopShelf 描述:

    Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.

    1、ok,首先使用VS 建立一个控制台 程序,使用Nuget 搜索 TopShelf 引用 TopShelf 和 TopShelf.Log4Net

    2、写入代码:

     1 public class TownCrier
     2 {
     3     readonly Timer _timer;
     4     public TownCrier()
     5     {
     6         _timer = new Timer(1000) {AutoReset = true};
     7         _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} an all is well", DateTime.Now);
     8     }
     9     public void Start() { _timer.Start(); }
    10     public void Stop() { _timer.Stop(); }
    11 }
    12 
    13 public class Program
    14 {
    15     public static void Main()
    16     {
    17         HostFactory.Run(x =>                                 
    18         {
    19             x.Service<TownCrier>(s =>                       
    20             {
    21                s.ConstructUsing(name=> new TownCrier());     
    22                s.WhenStarted(tc => tc.Start());  //指定此服务的启动函数            
    23                s.WhenStopped(tc => tc.Stop());   //指定此服务的终止函数            
    24             });
    25             x.RunAsLocalSystem();                            
    26 
    27             x.SetDescription("这是一个测试的服务 作用就是控制台输出~~");       // 服务描述
    28             x.SetDisplayName("_Rufus_Test_Winservices");                   //服务显示名字   
    29             x.SetServiceName("_Rufus_Test_winServices");                   //服务名字   
    30         });                                                  
    31     }
    32 }

    3、编译

    4、找到你编译成功的exe程序 执行cmd命令 (ps: 需要管理员权限)

    XXXXX install    (xxxx是你编译的程序名 例如 我的为 WinServerTest install)

    5、现在 查看 服务管理器 发现  _Rufus_Test_Winservices  已经注册到 里面 了,手动启动这个 服务即可。

  • 相关阅读:
    三层架构简单实例【转】
    排序 普通插入法排序
    排序 选择排序
    C#中的继承与覆盖
    排序 冒泡排序法
    c#使用Split分割字符串的几种方法
    GROUP BY,WHERE,HAVING之间的区别和用法
    递归 斐波那契数列
    【公众号系列】一文看懂税费改革
    【MM系列】SAP库龄报表逻辑理解
  • 原文地址:https://www.cnblogs.com/rufus-hua/p/3515097.html
Copyright © 2011-2022 走看看