• C#创建控制台项目引用Topshelf的方式,部署windows服务。


    上一篇是直接创建windows service服务来处理需求。调试可能会麻烦一点。把里面的逻辑写好了。然后受大神指点,用Topshelf会更好一些。

    来公司面试的时候问我,为什么要用stringbuilder,领导说,我平时用string拼字符串也挺好的呀。

    我那时候潜意识就是觉得学会加减法都是为了乘除法做准备的。实际上应该是stringbuilder效率会高一些吧。

    引用Topshelf的优势就是方便调试吧。因为你运行起来就是控制台界面。

    而且命名直接在.cs中就可以了。不需要在windows service的属性中对应改一些配置吧。个人心得。

    【开始简单介绍一下使用方法】

    1.新建一个控制台项目,只需要引用Topshelf.dll即可,为了日志输出显示,建议也引用Topshelf.Log4net.

    Visual Studio 点工具——>NuGet包管理器——>点程序包管理控制台

    程序安装命令:

    Install-Package Topshelf

    Install-Package Topshelf.Log4Net

    2.Program中Main()方法

      /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            private static void Main()
            {
                HostFactory.Run(conf =>
                {
                    conf.Service<AutoCancelService>(service =>
                    {
                        service.ConstructUsing(name => new AutoCancelService());
                        service.WhenStarted(tc => tc.OnStart());
                        service.WhenStopped(tc => tc.OnStop());
                    });
    
                    conf.RunAsLocalSystem();
    
                    conf.SetDescription("自动取消XXX");                     //服务的描述
                    conf.SetDisplayName("Auto dosomesthing Service");      
                    conf.SetServiceName("Auto dosomesthing Service");      
                    conf.StartAutomatically(); // Start the service automatically 自动模式
                    
                });
            }

    然后对应建立AutoCancelService类,来写逻辑代码。注意类中一定要对应有OnStart()和 OnStop()方法,不然会报错:Lamdba表达式没有返回值之类的。

      public class AutoCancelService
      {
         
            public void OnStart()
            {
                this.WriteLog("自动取消服务:【服务开启】");
           //在这里写逻辑代码
    } public void OnStop() { this.WriteLog("自动取消服务:【服务关闭】"); } }
    运行起来的界面是这样的

    【关于部署】

    用管理员权限打开Cmd,定位到程序所在目录:
    安装:
    ProductDownloadService.exe install
    卸载:
    ProductDownloadService.exe uninstall

    【例如】
    1.C盘下新建WindowService文件夹,将最新生辰的Debug内容拷贝到该文件夹。
    2.管理员运行CMD
    3.命令在C:盘符下执行

    【回退上级文件夹】
    CD..

    【安装命令】
    WindowServiceProductDownloadService.exe install

    【卸载命令】
    WindowServiceProductDownloadService.exe uninstall

    目前我自动执行用timer,还可以用cron表达式,更灵活。等我学会再写一篇详细介绍。

    如果看完对你有帮助可以留言,告诉我一下。我写了这么久博客,初衷只是为了帮自己记录知识。常来博客园感受氛围,受熏陶。

    从前我手机浏览器主页是新闻,现在我换成博客园主页了,公交车上随手打开可能就看到哪个知识点会被吸引,肯定是要比阅读一些垃圾新闻更有用。

    我只是要求自己保证每个月记录一篇有趣的内容就好了,最近感觉学到了很多知识,如果可以的话,我多整理一些文档。

    路过的大神朋友希望多鼓励,多指点,路过的新手朋友希望对你有帮助。

    
    
    
     
  • 相关阅读:
    Python3 使用requests请求,解码时出错:'utf8' codec can't decode byte 0x83 in position 1: invalid start byte
    快速上手阿里云oss SDK
    peewee 通俗易懂版
    gunicorn开启、关闭和重启
    Vector和ArrayList区别
    Hibernate与MyBatis
    redis缓存
    Innodb学习
    基本数据结构-图
    基本数据结构-树
  • 原文地址:https://www.cnblogs.com/Early-Bird/p/9402122.html
Copyright © 2020-2023  润新知