使用C#创建windows服务续之使用Topshelf优化Windows服务
程序员文章站
2022-12-25 20:11:24
前言: 之前写了一篇“使用C#创建windows服务”,https://www.cnblogs.com/huangwei1992/p/9693167.html,然后有博友给我推荐了一个开源框架Topshelf。 写了一点测试代码,发现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框架下进行服务的这些操作相对而言就简单多了
安装:topshelf.cloudimageload.exe install
启动:topshelf.cloudimageload.exe start
卸载:topshelf.cloudimageload.exe uninstall
操作界面如下:(注意:必须用管理员身份运行命令提示符)
在这里只贴出了安装命令的截图,其他命令相信就不用多说了。
查看服务列表,这时我们的服务就已经安装成功了
参考链接:
http://www.cnblogs.com/jys509/p/4614975.html
下一篇: 机器人抢饭碗前会和你并肩作战一段时间