一、创建windows服务项目
创建完成后结构,如:

其中,Program.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text; namespace WindowsService1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}

Service1.cs代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text; namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
} protected override void OnStop()
{
}
}
}

此时,Service1.cs设计视图默认属性为:

二、配置windows服务,添加安装程序
(以上时默认初始化展示,为方便演示,下面将服务文件名Service1.cs改为XFKFinanceAccService.cs,服务名称也改成了XFKFinanceAccService)
回到XFKFinanceAccService.cs设计视图,空白处右键==》添加安装程序,如:

可以看到,在ProjectInstaller安装程序文件的设计视图里,有两个名为serviceInstaller1和serviceProcessInstaller1的组件,设置它们的属性,如:


三、编写windows服务代码
服务设置好以后,进入XFKFinanceAccService.cs代码视图,开始实现处理逻辑。
示例一:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using XFKFinanceAccountsSys.BussinessLogic;
using XFKFinanceAccountsSys.Common; namespace XFKFinanceAccountsSys.WindowsService
{
public partial class XFKFinanceAccService : ServiceBase
{
DateTime lastDt = DateTime.Now.AddDays(-1);
Thread thread = null;
public XFKFinanceAccService()
{
InitializeComponent();
LogHelper.WriteLog("---初始化windows服务!!!");
} protected override void OnStart(string[] args)
{
LogHelper.WriteLog("---启动windows服务!!!");
thread = new Thread(new ThreadStart(AutoGenElapsed));
thread.IsBackground = true;
thread.Start();
} protected override void OnStop()
{
LogHelper.WriteLog("Stop");
if (thread != null)
{
if (thread.ThreadState == System.Threading.ThreadState.Running)
{
thread.Abort();
}
}
} private void AutoGenElapsed()
{
LogHelper.WriteLog("---进入windows服务!!!");
while (true)
{
//服务开始处理时间
string startTime = ConfigurationManager.AppSettings["StartTime"];
//每次处理完间隔时间
int interval = int.Parse(ConfigurationManager.AppSettings["Interval"]); try
{
//一天执行一次
if (DateTime.Now.DayOfYear == lastDt.DayOfYear + 1)
{
//到达处理时间时,任务开始处理数据
if (DateTime.Now > Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + startTime))
{
/********** 处理逻辑主体 Begin***********/ /********** 处理逻辑主体 End***********/
//处理完后时间改为当前时间,下一次不再处理
lastDt = DateTime.Now;
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog("error" + ex);
}
finally
{
Thread.Sleep(interval * 1000);
}
}
}
}
}

 示例二(启用定时器):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using XFKFinanceAccountsSys.BussinessLogic;
using XFKFinanceAccountsSys.Common; namespace XFKFinanceAccountsSys.WindowsService
{
public partial class XFKFinanceAccService : ServiceBase
{
DateTime lastDt = DateTime.Now.AddDays(-1);
Thread thread = null;
public XFKFinanceAccService()
{
InitializeComponent();
LogHelper.WriteLog("---初始化windows服务!!!"); //启用定时器
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += timer_Elapsed;
timer.Interval = 5000;//每5秒执行一次
timer.Enabled = true;
} void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
LogHelper.WriteLog("---进入windows服务!!!");
//服务开始处理时间
string startTime = ConfigurationManager.AppSettings["StartTime"];
//每次处理完间隔时间
int interval = int.Parse(ConfigurationManager.AppSettings["Interval"]); try
{
//一天执行一次
if (DateTime.Now.DayOfYear == lastDt.DayOfYear + 1)
{
//到达处理时间时,任务开始处理数据
if (DateTime.Now > Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + startTime))
{
/********** 处理逻辑主体 Begin***********/ /********** 处理逻辑主体 End***********/
//处理完后时间改为当前时间,下一次不再处理
lastDt = DateTime.Now;
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog("error" + ex);
}
finally
{
Thread.Sleep(interval * 1000);
}
} protected override void OnStart(string[] args)
{
LogHelper.WriteLog("---启动windows服务!!!");
} protected override void OnStop()
{
LogHelper.WriteLog("---停止windows服务!!!");
} }
}

在项目中加入配置文件App.config,需加入下面配置:

我们可以修改程序入口代码,以便可以将服务定制化,如:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using XFKFinanceAccountsSys.BussinessLogic;
using XFKFinanceAccountsSys.WindowsService.Model; namespace XFKFinanceAccountsSys.WindowsService
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); string dataBaseXmlFile = System.AppDomain.CurrentDomain.BaseDirectory + "../../ConfigXml\\DataBase.xml";
XFK.AFX1.Common.DB.ORM.Setting.Instance().DatabaseMapFile = dataBaseXmlFile; if (args.Length > 0)
{
//如果入口参数不为空,则运行服务
if (args[0].ToLower() == "/s" || args[0].ToLower() == "-s")
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new XFKFinanceAccService()
};
ServiceBase.Run(ServicesToRun);
}
}
else
{
//如果入口参数为空,则进入到服务操作界面
Application.Run(new OperationForm());
}
} }
}

OperationForm窗口:

我们可以在这个winform窗体中增加需要的功能,如安装/卸载服务、查看/编辑数据等。
当然,我们也可以用DOS命令安装和卸载服务,如:
安装:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  "E:\WORK\对账系统\XFKFinanceAccountsSys20170627\XFKFinanceAccountsSys.WindowsService\bin\Debug\XFKFinanceAccountsSys.WindowsService.exe"
卸载:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -U E:\WORK\对账系统\XFKFinanceAccountsSys20170627\XFKFinanceAccountsSys.WindowsService\bin\Debug\XFKFinanceAccountsSys.WindowsService.exe

参考资料:
http://www.cnblogs.com/xujie/p/5695673.html
http://blog.csdn.net/xiaoy_h/article/details/26090277(内存共享)

windows服务总结的更多相关文章

  1. 基于SignalR实现B/S系统对windows服务运行状态的监测

    通常来讲一个BS项目肯定不止单独的一个BS应用,可能涉及到很多后台服务来支持BS的运行,特别是针对耗时较长的某些任务来说,Windows服务肯定是必不可少的,我们还需要利用B/S与windows服务进 ...

  2. C#创建、安装、卸载、调试Windows Service(Windows 服务)的简单教程

    前言:Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面.这 ...

  3. 玩转Windows服务系列汇总

    玩转Windows服务系列汇总 创建Windows服务 Debug.Release版本的注册和卸载及其原理 无COM接口Windows服务启动失败原因及解决方案 服务运行.停止流程浅析 Windows ...

  4. 玩转Windows服务系列——给Windows服务添加COM接口

    当我们运行一个Windows服务的时候,一般情况下,我们会选择以非窗口或者非控制台的方式运行,这样,它就只是一个后台程序,没有界面供我们进行交互. 那么当我们想与Windows服务进行实时交互的时候, ...

  5. 玩转Windows服务系列——使用Boost.Application快速构建Windows服务

    玩转Windows服务系列——创建Windows服务一文中,介绍了如何快速使用VS构建一个Windows服务.Debug.Release版本的注册和卸载,及其原理和服务运行.停止流程浅析分别介绍了Wi ...

  6. 玩转Windows服务系列——Debug、Release版本的注册和卸载,及其原理

    Windows服务Debug版本 注册 Services.exe -regserver 卸载 Services.exe -unregserver Windows服务Release版本 注册 Servi ...

  7. C# 开发windows服务的一些心得

    最近在做一个windows服务的项目,发现并解决了一些问题,拿出来和大家分享一下,以下windows服务简称“服务” 文章会在适合时间更新,因为朋友们在不断提出新的意见或思路,感谢-.- 1.服务如何 ...

  8. 使用topshelf包装redis为windows服务

           Redis服务端目前用的是控制台程序运行,部署的时候能作为windows服务后台运行感觉更好.找到一篇文章Running Redis as a Windows Service,利用win ...

  9. 编写Windows服务疑问1:操作过程

    Windows 服务开发平时不太受人关注,毕竟那是高大上的项目类型,平常需求也用不上,很多老掉牙的家伙也只知有WinForm,仍不知有WPF,更别说Windows 服务了,正如陶渊明所写的,“不知有汉 ...

  10. C# windows服务制作(包括安装及卸载)

    开篇语 因工作内容需要做一个windows服务,此前并没有相关经验,所以做了一个demo来跑跑这个梗(高手跳过,需要的来踩)- 效果如下:打开服务,可以找到我们新增的一个windows服务,这个dem ...

随机推荐

  1. Linux内核调试方法总结之sysrq

    sysrq [用途] Sysrq被称为”魔术组合键”, 是内建于Linux内核的调试工具.只要内核没有完全锁住,不管内核在做什么事情,使用这些组合键都可以搜集包括系统内存使用.CPU任务处理.进程运行 ...

  2. HTTP中GET请求与POST请求的区别

    GET和POST是HTTP请求的两种基本方法.最直观的区别就是GET把参数包含在URL中,POST通过request body传递参数.但这只是表象,或者说只是现象,并不是核心.本文将细细谈谈对它们的 ...

  3. JDK与CGlib动态代理的实现

    应用的原型为 执行者:房屋中介Agency(分为JDKAgency.CGlibAgency) 被代理对象:程序员Programmer 被代理对象的实现接口:租户Tenement(CGlibAgency ...

  4. leetcode探索高级算法

    C++版 数组和字符串 正文 链表: 正文 树与图: 树: leetcode236. 二叉树的最近公共祖先 递归(先序) leetcode124二叉树最大路径和 递归 图: leetcode 547朋 ...

  5. rally测试opentack------安装部署和简单实践

    1,下载 git clone git://git.openstack.org/openstack/rally 或者 git clone https://git.openstack.org/openst ...

  6. 一个伪静态与404重定向例子(房产网),.htaccess文件内容

    ErrorDocument 404 /404.phpRewriteEngine OnRewriteBase /RewriteRule ^(.*)\.(asp|aspx|asa|asax|dll|jsp ...

  7. Linux系统管理_主题02 :管好文件(1)_2.1 切换、创建和删除目录_cd_mkdir_rmdir

    用法:cd [目录路径] 变换工作目录至制定目录路径,若[目录路径]参数省略则变换至使用者的 家目录, 其中[目录路径]可为绝对路径或相对路径 另外 "~" 在 Bash 中表示当 ...

  8. 转:SpringMVC 4.1 新特性(二)内容协商视图

    SpingMVC的内容协商支持三种方式: 使用后缀,如json.xml后缀和处理类型的关系可以自己定义 前面说的使用Accept头 在访问时request请求的参数,比如每次请求request都会加f ...

  9. maven 依赖原则

    maven 依赖原则 ###间接依赖路径最短优先 a->b->c1.0 a->e->f->c1.1 ====>c1.0 申明顺序优先 <!-- test1 - ...

  10. VMware中为CentOS配置静态ip并可访问网络-windows下的VMware

    首先确保虚拟网卡(VMware Network Adapter VMnet8)是开启的,然后在windows的命令行里输入“ipconfig /all”,找到VMware Network Adapte ...