windows服务总结
一、创建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服务总结的更多相关文章
- 基于SignalR实现B/S系统对windows服务运行状态的监测
通常来讲一个BS项目肯定不止单独的一个BS应用,可能涉及到很多后台服务来支持BS的运行,特别是针对耗时较长的某些任务来说,Windows服务肯定是必不可少的,我们还需要利用B/S与windows服务进 ...
- C#创建、安装、卸载、调试Windows Service(Windows 服务)的简单教程
前言:Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面.这 ...
- 玩转Windows服务系列汇总
玩转Windows服务系列汇总 创建Windows服务 Debug.Release版本的注册和卸载及其原理 无COM接口Windows服务启动失败原因及解决方案 服务运行.停止流程浅析 Windows ...
- 玩转Windows服务系列——给Windows服务添加COM接口
当我们运行一个Windows服务的时候,一般情况下,我们会选择以非窗口或者非控制台的方式运行,这样,它就只是一个后台程序,没有界面供我们进行交互. 那么当我们想与Windows服务进行实时交互的时候, ...
- 玩转Windows服务系列——使用Boost.Application快速构建Windows服务
玩转Windows服务系列——创建Windows服务一文中,介绍了如何快速使用VS构建一个Windows服务.Debug.Release版本的注册和卸载,及其原理和服务运行.停止流程浅析分别介绍了Wi ...
- 玩转Windows服务系列——Debug、Release版本的注册和卸载,及其原理
Windows服务Debug版本 注册 Services.exe -regserver 卸载 Services.exe -unregserver Windows服务Release版本 注册 Servi ...
- C# 开发windows服务的一些心得
最近在做一个windows服务的项目,发现并解决了一些问题,拿出来和大家分享一下,以下windows服务简称“服务” 文章会在适合时间更新,因为朋友们在不断提出新的意见或思路,感谢-.- 1.服务如何 ...
- 使用topshelf包装redis为windows服务
Redis服务端目前用的是控制台程序运行,部署的时候能作为windows服务后台运行感觉更好.找到一篇文章Running Redis as a Windows Service,利用win ...
- 编写Windows服务疑问1:操作过程
Windows 服务开发平时不太受人关注,毕竟那是高大上的项目类型,平常需求也用不上,很多老掉牙的家伙也只知有WinForm,仍不知有WPF,更别说Windows 服务了,正如陶渊明所写的,“不知有汉 ...
- C# windows服务制作(包括安装及卸载)
开篇语 因工作内容需要做一个windows服务,此前并没有相关经验,所以做了一个demo来跑跑这个梗(高手跳过,需要的来踩)- 效果如下:打开服务,可以找到我们新增的一个windows服务,这个dem ...
随机推荐
- Linux: Block Port With IPtables
由Internet和其他网络协议识别端口号,使计算机能够与其他人进行交互.每个Linux服务器都有一个端口号(参见/ etc / services文件) Block Incoming Port The ...
- django-admin 配置
本节讲django-admin配置方法: 1.在工程配置文件中(settings.py)中启用admin组件.确保有如下两行配置: 2.执行数据库迁移的命令,确保对应的表在数据库中已经添加了 #pyt ...
- 【MyBatis】从一千万记录中批量删除八百万条,耗时4m7s
批量删除主要借助了MySql的limit函数,其次用了in删除. 代码如下: package com.hy.action; import java.io.Reader; import java.uti ...
- nodejs服务端实现post请求
博客之前写过一篇php实现post请求的文章. 今天想到好久没有输出了,重新认识到输出的重要性.百般思索该写些什么?想来想去,想到了两点: 逐步熟练nodejs各种场景知识,针对mysql数据交互和f ...
- 发布机制-灰度发布-例子:QZone
ylbtech-发布机制-灰度发布-例子:QZone QZone是另外一个采用灰度发布的例子.大家都知道,QZone在过去的一年中改进是巨大的,从以前慢悠悠的老爷爷变成了一个充满青春活力的小伙子.其中 ...
- 浏览器输入url后发生的事情以及每步可以做的优化
首先总结下输入url按下回车后的大致流程: 查询url的ip地址. 建立tcp连接,连接服务器. 浏览器发起http/https请求. 服务器响应浏览器的请求. 网页的解析与渲染. 下面分析每个过程 ...
- Linux下的C的开发之GCC的初级使用
<span style="font-family: Arial, Helvetica, sans-serif; "><span style="white ...
- django中CBV加csrf_exempt函数问题
CSRF Token相关装饰器在CBV只能加到dispatch方法上 备注: 1. csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件. 2. c ...
- 封装Button ,封装UITableView,封装UICollectionView
---恢复内容开始--- 封装Button ,封装UITableView,封装UICollectionView: 1.实现Button的创建和点击事件不用分开操作处理; 2.实现UITableView ...
- C# AES的128位、192位、256位加密
C# AES的128位.192位.256位加密 AES加密原理,这里就不解释了,自行百度.这里主要细说AES的CBC加密模式下的128位.192位.256位加密区别,参考 对称加密和分组加密中的四 ...