• 使用Topshelf创建Windows服务


    本方式特点:代码简单,开源组件,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

  • 相关阅读:
    python向mysql中插入数字、字符串、日期总结
    selenium鼠标事件
    iOS hook
    网络抓包篇
    frida IOS环境搭建
    git
    $emit
    better-scroll无法滚动的问题。
    this.$nextTick()作用
    better-scroll
  • 原文地址:https://www.cnblogs.com/zeroone/p/4396565.html
Copyright © 2020-2023  润新知