使用C#创建windows服务续之使用Topshelf优化Windows服务
前言:
之前写了一篇“使用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框架下进行服务的这些操作相对而言就简单多了


使用C#创建windows服务续之使用Topshelf优化Windows服务的更多相关文章
- Quartz+TopShelf实现Windows服务作业调度
Quartz:首先我贴出来了两段代码(下方),可以看出,首先会根据配置文件(quartz.config),包装出一个Quartz.Core.QuartzScheduler instance,这是一个调 ...
- Windows Azure HandBook (2) Azure China提供的服务
<Windows Azure Platform 系列文章目录> 对于传统的自建数据中心,从底层的Network,Storage,Servers,Virtualization,中间层的OS, ...
- 使用Topshelf 开发windows服务
在业务系统中,我们为了调度一些自动执行的任务或从队列中消费一些消息,所以基本上都会涉及到后台服务的开发.如果用windows service开发,非常不爽的一件事就是:调试相对麻烦,而且你还需要了解 ...
- Windows Azure案例分析: 选择虚拟机或云服务?
作者 王枫 发布于2013年6月27日 随着云计算技术和市场的日渐成熟,企业在考虑IT管理和运维时的选择也更加多样化,应用也从传统部署方式,发展为私有云.公有云.和混合云等部署方式.作为微软核心的公有 ...
- rsync (windows 服务端,linux客户端)将windows上的数据同步到linux服务器,反之也可
一:总体概述. 1.windows上面首先装CW_rsync_Server.4.1.0_installer,安装时要输入的用户名密码要记住哦!接下来就是找到rsyncd.conf进入配置细节 2.li ...
- Windows Server 2016-命令行方式管理Windows服务
Microsoft Windows 服务(过去称为 NT 服务)允许用户创建可在其自身的 Windows 会话中长时间运行的可执行应用程序. 这些服务可在计算机启动时自动启动,可以暂停和重启,并且不显 ...
- topshelf 开发windows 服务资料
官方配置 http://docs.topshelf-project.com/en/latest/configuration/config_api.html#service-start-modes to ...
- Windows Azure中WebSite 网站, Cloud Service 云服务,Virtual Machine 虚拟机的比较
在Windows Azure服务平台里,Web Site特点是: 在Windows Azure上构建高度可扩展的Web站点. 快速.轻松部署一个高度可扩展的云环境,并且可以从很小的规模开始. 使用您所 ...
- quartz.net结合Topshelf实现windows service服务托管的作业调度框架
topshelf可以很简单方便的实现windows service服务,详见我的一篇博客的介绍 http://www.cnblogs.com/xiaopotian/articles/5428361.h ...
随机推荐
- AasyncTask中执行execute()还是executeOnExecutor()
executeOnExecutor()api 11 才出现的 并行的 效率比execute()高因为execute()是串行的 import android.app.Activity; import ...
- Nmap参数说明
Nmap(Network Mapper)是一款开放源代码的网络探测和安全审核工具.它的设计目标是快速地扫描大型网络,不适应于单一主机.Nmap使用检测IP数据包来确定访问的主机.提供的服务.数据包的类 ...
- 如何在C#中自定义自己的异常
在C#中所有的异常类型都继承自System.Exception,也就是说,System.Exception是所有异常类的基类. 总起来说,其派生类分为两种:1. SystemException类: 所 ...
- geoserver 通过代码实现发布地图服务
GeoServer:代码实现批量发布地图服务 利用GeoServer发布WCS服务,那么如果我有很多数据需要进行发布,这样利用GeoServer提供的UI界面进行操作显然很不显示.那能不能利用GeoS ...
- dbus通信与接口介绍
DBUS是一种高级的进程间通信机制.DBUS支持进程间一对一和多对多的对等通信,在多对多的通讯时,需要后台进程的角色去分转消息,当一个进程发消息给另外一个进程时,先发消息到后台进程,再通过后台进程将信 ...
- java如何从一段html代码中获取图片的src路径
java如何从一段html代码中获取图片的src路径 package com.cellstrain.icell.Test; import java.util.ArrayList;import java ...
- Part 5 - Django ORM(17-20)
https://github.com/sibtc/django-beginners-guide/tree/v0.5-lw from django.conf.urls import url from d ...
- ExtJS+SpringMVC文件上传与下载
说到文件上传.下载功能,网络上大多介绍的是采用JSP.SpringMVC或者Struts等开源框架的功能,通过配置达到文件上传.下载的目地.可是最近项目要用到文件上传与下载的功能,因为本项目框架采用开 ...
- sql左外连接、右外连接、group by、distinct(区别)、intersect(交叉)、通配符、having
连接条件可在FROM或WHERE子句中指定,建议在FROM子句中指定连接条件.WHERE和HAVING子句也可以包含搜索条件,以进一步筛选连接条件所选的行. 连接可分为以下几类 ...
- BSD Socket 通信
Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain ...