【Window Service】关于Window Service的两三事
引言
Window Service通常用于寄宿WCF服务或者定时作业.下面记录一下它的用法.
创建
创建Window Service项目后,可以看到Program和Service1类.Program是程序的主入口,而Service1则是我们逻辑实现的主要地方 ,两个关键方法是OnStart和OnStop,用于实现服务启动和结束时的逻辑.
安装
在Service1类的设计界面上右击,选择添加安装程序,就可以完成了安装程序的创建.
Nlog
Window Service作为一个后台程序,发生了什么错误很难获取的信息的,所以需要做个日志记录.下面做个示例,每3秒输出日志记录.
1.打开NuGet程序包管理界面,输入Nlog搜索,安装其中的Nlog和Nlog Configuration,接着在NLog.config做下修改,如下
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" /> <target xsi:type="Console" name="c" layout="[${longdate}][${level:uppercase=true}][${logger}]${message}${exception}" /> </targets> <rules
<logger name="*" minlevel="Debug" writeTo="f,c" />
</rules>
2.在Service1中使用Timer和Nlog类,实现每3秒输出日志记录,如下
public partial class Service1 : ServiceBase
{
readonly Logger logger = LogManager.GetCurrentClassLogger();
readonly Timer timer=new Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.AutoReset = true;
timer.Interval = ; //单位毫秒
timer.Elapsed+=timer_Elapsed;
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
logger.Info(DateTime.Now.ToShortTimeString());
}
//下面两个方法是为了方便调试而创建
public void Start()
{
OnStart(null); }
public void Stop()
{
OnStop();
}
}
部署
下面是安装和卸载脚本,分别保存成Bat文件,放在程序的根目录就可以.
@echo 安装服务
set svc_file=%cd%\WindowsServiceDemo.exe
sc create Service1 binpath= "%svc_file%" displayName= "Service1" depend= tcpip start= auto
net start Service1
@pause
@exit @echo 卸载服务
net stop Service1
sc delete Service1
@pause
@exit
调试
VS貌似没有提供给Window Service调试的工具,要测试只能通过实际部署才能看到效果,但是可以利用TopShell寄宿服务来达到调试的目的.
1. http://topshelf-project.com/ 可以下到最新的类库
2.新建一个控制台程序,引用上面的服务,TopShell,Nlog,就可以编码了,如下
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.UseNLog(); x.Service<Service1>(s =>
{
s.ConstructUsing(name => new Service1());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
}); x.SetServiceName("Service1");
x.SetDisplayName("Service1");
x.SetDescription("每3秒记录日志");
x.RunAsLocalSystem();
x.StartAutomatically();
}); }
3.运行控制台程序,可以看到
小结
本文简单介绍了Window Service从创建到调试的步骤.如有更好的建议,请不吝指教.
参考资料
C# 编写Windows Service(windows服务程序)
【Window Service】关于Window Service的两三事的更多相关文章
- 在Activity,Service,Window中监听Home键和返回键的一些思考,如何把事件传递出来的做法!
在Activity,Service,Window中监听Home键和返回键的一些思考,如何把事件传递出来的做法! 其实像按键的监听,我相信很多人都很熟练了,我肯定也不会说这些基础的东西,所以,前期,还是 ...
- [PWA] 9. Service worker registerion && service work's props, methods and listeners
In some rare cases, you need to ask user to refresh the browsser to update the version. Maybe becaus ...
- service: no such service mysqld 与MySQL的开启,关闭和重启
1.问题原因与解决办法 因为修改了MySQL临时文件的目录后,使用service mysqld restart重启MySQL出现如下错误: service: no such service mysql ...
- Failed to stop iptables.service: Unit iptables.service not loaded.
redhat 7 [root@lk0 ~]# service iptables stop Redirecting to /bin/systemctl stop iptables.service Fai ...
- window.onload和window.document.readystate的探究
在编写前端页面的时候,我们时常需要对页面加载的状态进行判断,以便进行相应的操作. 比如在移动端,时常需要在页面完全加载完成之前,先显示一个loading的图标,等待页面完成加载完成后,才显示出真正要展 ...
- window.location.href = window.location.href 跳转无反应 a 超链接 onclick 点击跳转无反应
错误写法 , 主要是在 href="#"这里 <a href="#" id="send" onclick="return b ...
- window.parent与window.openner区别介绍
今天总结一下js中几个对象的区别和用法: 首先来说说 parent.window与top.window的用法 "window.location.href"."locati ...
- window.parent 与 window.opener
window.parent针对iframe,window.opener针对window.open 父页面parent.jsp: <%@ page language="java" ...
- window.location和window.open
window.location和window.open的区别 window.location = "http://www.baidu.com" 跳转后有后退功能 window.lo ...
- JavaScript(Iframe、window.open、window.showModalDialog)父窗口与子窗口之间的操作
一.Iframe 篇 公共部分 //父对象得到子窗口的值 //ObjectID是窗口标识,ContentID是元素ID function GetValue(ObjectID,ContentID) { ...
随机推荐
- ExtJS4 给同一个formpanel不同的url
formpanel能够这样使用,api上的样例: var panel=Ext.create('Ext.form.Panel', { title: 'Simple Form', bodyPadding: ...
- 爬取豆瓣电影信息保存到Excel
from bs4 import BeautifulSoup import requests import html.parser from openpyxl import Workbook,load_ ...
- 微信公众号的搭建-第四天(2)-获取并缓存access_token
1. 什么是access_token? 为了使第三方开发者能够为用户提供更多更有价值的个性化服务,微信公众平台 开放了许多接口,包括自定义菜单接口.客服接口.获取用户信息接口.用户分组接口.群发接口等 ...
- 剑指offer 面试3题
面试3题: 题:数组中重复的数字 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内. 数组中某些数字是重复的,但不知道有几个数字是重复的.也不知道每个数字重复几次.请找出数组中任意一个重复 ...
- python中的逻辑操作符
python中主要有三个逻辑操作符,分别是:and.or.not. and:且,所有人为真才为真. or:或,一个为正就是真. not:非,取反. >>> print(3>2 ...
- Boostrap常用组件英文名
dropdownlisttabsearchVertical TabSidebar with tabssidebarExpandable Panel ListFiltered Attendees Lis ...
- VM and Docker Container
https://www.zhihu.com/question/48174633 在开始讨论前,先抛出一些问题,可先别急着查看答案,讨论的过程可以让答案更有趣,问题如下: Docker 容器有自己的ke ...
- JAVA 判断对象内容是否含有空值
简单判断对象是否含有NULL值,以及信息描述. package com.sicdt.sicsign.bill.api.util; import java.lang.reflect.Invocation ...
- c++ boost库学习二:内存管理->智能指针
写过C++的人都知道申请和释放内存组合new/delete,但同时很多人也会在写程序的时候忘记释放内存导致内存泄漏.如下所示: int _tmain(int argc, _TCHAR* argv[]) ...
- 如何去掉Intellij IDEA过多的警告 设置警告级别
Intellij IDEA的代码提示系统很强大,根据严格的代码规范,包括简洁程度,运行效率,潜在bug提前发现等等给你做出了除编译器之外的大量额外提示.但这些提示有时会给我们带来困扰,比如弄的界面很乱 ...