使用C#创建windows服务续之使用Topshelf优化Windows服务

简介: 前言:之前写了一篇“使用C#创建windows服务”,https://www.cnblogs.com/huangwei1992/p/9693167.html,然后有博友给我推荐了一个开源框架Topshelf。

前言:

之前写了一篇“使用C#创建windows服务”,https://www.cnblogs.com/huangwei1992/p/9693167.html,然后有博友给我推荐了一个开源框架Topshelf。

写了一点测试代码,发现Topshelf框架确实在创建windows服务上非常好用,于是就对我之前的代码进行了改造。

开发流程:

1.在不使用Topshelf框架的情况下,我们需要创建Windows服务程序,在这里我们只需要创建一个控制台程序就行了

2.添加引用

使用程序安装命令:

  • Install-Package Topshelf

直接在NuGet包管理器中搜索 Topshelf,点击安装即可:

3.新建核心类CloudImageManager

主要方法有三个:LoadCloudImage、Start、Stop,直接贴代码

/// <summary>
    /// 功能描述    :卫星云图下载管理器  
    /// 创 建 者    :Administrator
    /// 创建日期    :2018/9/25 14:29:03 
    /// 最后修改者  :Administrator
    /// 最后修改日期:2018/9/25 14:29:03 
    /// </summary>
    public class CloudImageManager
    {
        private string _ImagePath = System.Configuration.ConfigurationManager.AppSettings["Path"];
        private Timer _Timer = null;
        private double Interval = double.Parse(System.Configuration.ConfigurationManager.AppSettings["Minutes"]);
        public CloudImageManager()
        {
            _Timer = new Timer();
            _Timer.Interval = Interval * 60 * 1000;
            _Timer.Elapsed += _Timer_Elapsed;
        }
        void _Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            StartLoad();
        }
        /// <summary>
        /// 开始下载云图
        /// </summary>
        private void StartLoad()
        {
            LoadCloudImage();
        }
        public void Start()
        {
            StartLoad();
            _Timer.Start();
        }
        public void Stop()
        {
            _Timer.Stop();
        }
        /// <summary>
        /// 下载当天所有卫星云图
        /// </summary>
        private void LoadCloudImage()
        {
            CreateFilePath();//判断文件夹是否存在,不存在则创建
            //获取前一天日期
            string lastYear = DateTime.Now.AddDays(-1).Year.ToString();
            string lastMonth = DateTime.Now.AddDays(-1).Month.ToString();
            if (lastMonth.Length < 2) lastMonth = "0" + lastMonth;
            string lastDay = DateTime.Now.AddDays(-1).Day.ToString();
            if (lastDay.Length < 2) lastDay = "0" + lastDay;
            //获取当天日期
            string year = DateTime.Now.Year.ToString();
            string month = DateTime.Now.Month.ToString();
            if (month.Length < 2) month = "0" + month;
            string day = DateTime.Now.Day.ToString();
            if (day.Length < 2) day = "0" + day;
            //设置所有文件名
            string[] dates0 = { lastYear + "/" + lastMonth + "/" + lastDay, year + "/" + month + "/" + day };
            string[] dates = { lastYear + lastMonth + lastDay, year + month + day };
            string[] hours = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };
            string[] minutes = { "15", "45" };
            int hLength = hours.Count();
            //遍历下载当天所有在线云图
            for (int i = 0; i < 2; i++)
            {
                string date = dates[i];
                string date0 = dates0[i];
                for (int j = 0; j < hLength; j++)
                {
                    string hour = hours[j];
                    for (int k = 0; k < 2; k++)
                    {
                        string minute = minutes[k];
                        string imageUrl = @"http://image.nmc.cn/product/" + date0 + @"/WXCL/SEVP_NSMC_WXCL_ASC_E99_ACHN_LNO_PY_" + date + hour + minute + "00000.JPG";
                        string[] s = imageUrl.Split('/');
                        string imageName = s[s.Count() - 1];

                        HttpWebRequest request = HttpWebRequest.Create(imageUrl) as HttpWebRequest;
                        HttpWebResponse response = null;
                        try
                        {
                            response = request.GetResponse() as HttpWebResponse;
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        if (response.StatusCode != HttpStatusCode.OK) continue;
                        Stream reader = response.GetResponseStream();
                        FileStream writer = new FileStream(_ImagePath + imageName, FileMode.OpenOrCreate, FileAccess.Write);
                        byte[] buff = new byte[512];
                        int c = 0; //实际读取的字节数
                        while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                        {
                            writer.Write(buff, 0, c);
                        }
                        writer.Close();
                        writer.Dispose();
                        reader.Close();
                        reader.Dispose();
                        response.Close();
                    }
                }
            }
        }
        /// <summary>
        /// 判断文件夹是否存在,不存在则创建
        /// </summary>
        private void CreateFilePath()
        {
            if (Directory.Exists(_ImagePath))
            {
                ClearImages();
                return;
            }
            else
            {
                Directory.CreateDirectory(_ImagePath);
            }
        }
        /// <summary>
        /// 清空文件夹下所有文件
        /// </summary>
        private void ClearImages()
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(_ImagePath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

 然后在Program.cs中调用:

static void Main(string[] args)
        {
            HostFactory.Run(x =>                                 //1
            {
                x.Service<CloudImageManager>(s =>                        //2
                {
                    s.ConstructUsing(name => new CloudImageManager());     //3
                    s.WhenStarted(tc => tc.Start());              //4
                    s.WhenStopped(tc => tc.Stop());               //5
                });
                x.RunAsLocalSystem();                            //6

                x.SetDescription("卫星云图实时下载工具");        //7
                x.SetDisplayName("CloudImageLoad");                       //8
                x.SetServiceName("CloudImageLoad");                       //9
            });
        }

可以看到调用的时候主要涉及到CloudImageManager类中的构造函数、Start方法以及Stop方法

安装、运行和卸载:

在Topshelf框架下进行服务的这些操作相对而言就简单多了

安装:Topshelf.CloudImageLoad.exe install
启动:Topshelf.CloudImageLoad.exe start
卸载:Topshelf.CloudImageLoad.exe uninstall
操作界面如下:(注意:必须用管理员身份运行命令提示符)
在这里只贴出了安装命令的截图,其他命令相信就不用多说了。
查看服务列表,这时我们的服务就已经安装成功了
 
参考链接:
http://www.cnblogs.com/jys509/p/4614975.html
目录
相关文章
|
1月前
|
Java 数据库 C#
C#winforms实现windows窗体人脸识别
C#winforms实现windows窗体人脸识别
30 0
|
1月前
|
Linux Shell Windows
通过Linux挂载Windows端NFS服务实现板端Linux传输文件到PC
通过Linux挂载Windows端NFS服务实现板端Linux传输文件到PC
|
1月前
|
存储 安全 数据安全/隐私保护
Windows部署WebDAV服务并映射到本地盘符实现公网访问本地存储文件
Windows部署WebDAV服务并映射到本地盘符实现公网访问本地存储文件
270 0
|
2月前
|
自然语言处理 C# Windows
C#开源免费的Windows右键菜单管理工具
C#开源免费的Windows右键菜单管理工具
|
2月前
|
Java Unix 应用服务中间件
使用java service wrapper把windows flume做成服务
使用java service wrapper把windows flume做成服务
|
2月前
|
Windows
修改Windows服务的配置
修改Windows服务的配置
|
27天前
|
Shell Windows
Windows服务器 开机自启动服务
Windows服务器 开机自启动服务
14 0
|
5天前
|
网络协议 安全 测试技术
Windows安装禅道系统结合Cpolar实现公网访问内网BUG管理服务
Windows安装禅道系统结合Cpolar实现公网访问内网BUG管理服务
|
1月前
|
Windows
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
115 0
|
2月前
|
安全 数据安全/隐私保护 Windows
Windows系统搭建VisualSVN实现公网访问本地服务
Windows系统搭建VisualSVN实现公网访问本地服务
50 0