首页 > Windows开发 > 详细

通过TopShelf简单创建windows service

时间:2019-11-05 14:59:52      阅读:95      评论:0      收藏:0      [点我收藏+]

目前很多项目都是B/S架构的,我们经常会用到webapi、MVC等框架,实际项目中可能不仅仅是一些数据的增删改查,需要对数据进行计算,但是将计算逻辑放到api层又会拖累整个项目的运行速度,从而会写一些计划任务(使用quartz.net,在上一篇中已经提到)将需要计算的数据提前计算并入库,理论上api层需要做的只是增删改查,从而加快程序运行速度。

        传统windows 服务需要创建一个windows service 项目,我自己没有用过,但是看过别人的整个开发流程,感觉及其繁杂并且不容易调试。

        使用topshelf可以很快的创建一个服务,而我们需要做的只是创建一个控制台程序,调试成本也大大降低。

        步骤如下:

  1. 首先还是通过nuget添加topshelf程序集技术分享图片
  2. 添加ServiceRunner类,这里用Quartz做例子。当然不仅仅适用于次,也可以用于wcf等。

    using Quartz;
    using Quartz.Impl;
    using Topshelf;
    
    namespace KfqPointService
    {
        public sealed class ServiceRunner : ServiceControl, ServiceSuspend
        {
            private readonly IScheduler scheduler;
    
            public ServiceRunner()
            {
                scheduler = StdSchedulerFactory.GetDefaultScheduler();
            }
    
            public bool Start(HostControl hostControl)
            {
                scheduler.Start();
                return true;
            }
    
            public bool Stop(HostControl hostControl)
            {
                scheduler.Shutdown(false);
                return true;
            }
    
            public bool Continue(HostControl hostControl)
            {
                scheduler.ResumeAll();
                return true;
            }
    
            public bool Pause(HostControl hostControl)
            {
                scheduler.PauseAll();
                return true;
            }
        }
    }
    
    

     

  3. 在程序入口中添加代码

    using System.Configuration;
    using KfqPointService;
    using Topshelf;
    
    namespace LfsZqHbInterface
    {
        class Program
        {
            static void Main(string[] args)
            {
                //LogWriter.Debug("Begin Service");
                HostFactory.Run(x =>
                {
                    x.Service<ServiceRunner>();
                    x.SetDescription(ConfigurationManager.AppSettings["Description"]);
                    x.SetDisplayName(ConfigurationManager.AppSettings["DisplayName"]);
                    x.SetServiceName(ConfigurationManager.AppSettings["ServiceName"]);
                    x.EnablePauseAndContinue();
                });
            }
        }
    }
    
    
  4. 将Windows服务安装到服务器上

        (1)依次打开服务文件夹以管理员权限运行powershell,并进入服务所在文件夹。

        技术分享图片

        (2)输入.\文件名.exe install 回车安装此服务,如下图所示

        技术分享图片

        出现此场景为安装成功,此时大功告成,打开服务面板就可看到我们刚刚安装的服务。

通过TopShelf简单创建windows service

原文:https://www.cnblogs.com/panxixi/p/11798241.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!