一、查看已有的Windows服务

选择菜单“开始”-〉“控制面板”-〉“管理工具”-〉“服务”来查看现有系统中的服务

二、C#中创建 Windows 服务

1、Visual Studio=> 新建 => 项目 => Windows 服务

2、重命名Service1.cs文件名为容易识别功能的文件名,这里我重命名成 MyFirstWinService.cs,如果类名改了,需要在 Program.cs文件的 Main() 方法里面的 new 对象也相应改过来

3、在此文件的设计视图中右键,在弹出的菜单中选择添加安装程序

4、项目会自动生成安装文件 ProjectInstaller.cs ,并且分别设置 serviceIntaller1 与 serviceProcessInstaller1 的属性。

5、到这里,服务的安装程序与框架已经搭建完毕

三、Windows服务的安装

1、新建安装服务的批处理文件

Install.bat

 

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe
Net Start ServiceTest

2、新建卸载服务的批处理文件

Uninstall.bat

 

net stop ServiceTest
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe

3、将批处理文件放入项目的bin->Debug文件夹下面,这样就可以方便使用程序控制服务的安装和卸载。

4、双击运行 Install.bat 进行自动安装 Windows 服务

5、安装成功后,可以进入Windows 服务 管理器,对刚才安装的服务设置启动方式:

新安装的服务一般是不会启动的,需要我们 点击上图中的启动按钮进行启动

四、Windows 服务开发过程中的调试

通过附加进程的方式调试Windows 服务,此方法必须先把写好的服务进行编译生成可执行的exe安装程序,并安装启动服务后,才可以进行附加此服务进程。

1、首先要对服务进行安装,然后启动服务。

2、打开VS项目,选择菜单 调试->附加到进程 选项,选择你的服务进程(如果找不到可以勾选 显示所有用户进程 选项)就可以了。如下图:

windows 服务实例:

每隔设置时间执行某段代码

internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new OrderUpdateService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

重点code:

using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;
using CRM.Services.Service;
using Castle.Windsor;
using Crm.DataSync.Installer;
using log4net;

public partial class OrderUpdateService : ServiceBase
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(OrderUpdateService));
        private static Timer _timer;
        private static bool _timerRunning;
        private static Timer _signTimer;
        private static bool _signTimerRunning;

static readonly OrderUpdateNew Service = new OrderUpdateNew();

public OrderUpdateService()
        {
            InitializeComponent();
        }

protected override void OnStart(string[] args)
        {
            try
            {
                Log.Info("service started");

var container = new WindsorContainer();
                container.Install(new GlobalInstaller());

var intervalStr = ConfigurationManager.AppSettings["Interval"];
                int interval = 60;
                int t;
                if (int.TryParse(intervalStr, out t))
                {
                    interval = t;
                }

var period = interval * 60000;
                _timer = new Timer(timer_Elapsed);
                _timer.Change(2000, period);

int mandatoryInterval = 5;
                intervalStr = ConfigurationManager.AppSettings["MandatoryInterval"];
                if (int.TryParse(intervalStr, out t))
                {
                    mandatoryInterval = t;
                }
                period = mandatoryInterval * 60000;
                _signTimer = new Timer(MandatorySignHandler);
                _signTimer.Change(2000, period);
            }
            catch (Exception ex)
            {
                Log.Error("", ex);
            }
        }

protected override void OnStop()
        {
            try
            {
                Log.Info("service stopped");
            }
            catch (Exception ex)
            {
                Log.Error("", ex);
            }
        }

void timer_Elapsed(object sender)
        {
            try
            {
                if (_timerRunning) return;
                _timerRunning = true;

var service = Service;
                if (service != null && PassRules())
                {
                    service.UpdateData();
                }
                _timerRunning = false;
            }
            catch (Exception ex)
            {
                Log.Error("timer exception", ex);
            }

}

void MandatorySignHandler(object sender)
        {
            const string title = "客户确认签收订单处理";
            Log.Info(title + "begin");
            try
            {
                var service = Service;
                if (service != null)
                {
                    service.UpdateMandatorySignedOrder();
                }
            }
            catch (Exception ex)
            {
                Log.Error(title, ex);
            }
            Log.Info(title + "end");
        }

bool PassRules()
        {
            var now = DateTime.Now;
            int hour = now.Hour;
            if (hour >= 0 && hour <= 5
                || (hour >= 22 && hour <= 24)) return false;
            return true;
        }
    }

C# Windows服务的创建、安装、调试的更多相关文章

  1. windows service 的创建 安装 调试 错误回发

    关于如何快速创建一个windows服务 1.在vs中创建windows服务 名称:你要写的服务名称 位置:创建服务所在的位置 点击确定 2.代码编写 3.添加安装程序 点击添加安装程序出现 分别右击设 ...

  2. C# windows服务的创建与调试

    Windows Service这一块并不复杂,但是注意事项太多了,网上资料也很凌乱,偶尔自己写也会丢三落四的.所以本文也就产生了,本文不会写复杂的东西,完全以基础应用的需求来写,所以不会对Window ...

  3. 【转】C# windows服务的创建与调试

    Windows Service这一块并不复杂,但是注意事项太多了,网上资料也很凌乱,偶尔自己写也会丢三落四的.所以本文也就产生了,本文不会写复杂的东西,完全以基础应用的需求来写,所以不会对Window ...

  4. windows服务的创建、安装、调试全过程及引发的后续学习

    前几天做项目的时候需要用到window服务,研究一段时间,算是掌握了最基本的使用方法吧,现总结如下: 引言:在项目过程中碰到一个问题:需要不断的扫描一个大型数据库表,并获取dataset,以便做后续的 ...

  5. C# Windows Service服务的创建和调试

    前言 关于Windows服务创建和调试的文章在网络上的很多文章里面都有,直接拿过来贴在这里也不过仅仅是个记录,不会让人加深印象.所以本着能够更深刻了解服务项目的创建和调试过程及方法的目的,有了这篇记录 ...

  6. 关于windows服务的编写/安装/与调试

    前注: 首先,这篇文章是从网上转过来的,因为最近有个项目,需要编写一个Windows Service来定时执行程序,网上很容易找到了这篇文章,大概看了一下,文章讲的还是很详细的.不过这篇文章应该是.n ...

  7. 玩转Windows服务系列——创建Windows服务

    创建Windows服务的项目 新建项目->C++语言->ATL->ATL项目->服务(EXE) 这样就创建了一个Windows服务项目. 生成的解决方案包含两个项目:Servi ...

  8. 玩转Windows服务系列——创建Windows服务

    原文:玩转Windows服务系列——创建Windows服务 创建Windows服务的项目 新建项目->C++语言->ATL->ATL项目->服务(EXE) 这样就创建了一个Wi ...

  9. windows服务的创建、安装和调试

    1.创建 windows服务 项目   文件 -> 新建项目 -> 已安装的模板 -> Visual C# -> windows ,在右侧窗口选择"windows 服 ...

随机推荐

  1. Visual Prolog 的 Web 专家系统 (7)

    GENI核心 -- 推理引擎(1)知识表示 GOAL最后一句是谓语infer(),它的含义是"论证". 因此,,进GENI核心,执行视图推理引擎. infer() infer(): ...

  2. PHP扩展memcache模

    研究yii当配套部件,发现自己PHP甚至不支持memcache该模块,于是,我就展开位. 本机环境:win8.1 开发环境:php 5.5  第一步:先把所需的文件包下载全然,我已经打包好,这里能够下 ...

  3. effective c++ 条款12 copy all parts of an object

    这经常发生在更改代码的时候,当有自己的copy 赋值函数或者copy 构造函数时,编译器就不会维护这两个函数.导致发生遗忘. 可能出现的场景 class Customer { private: std ...

  4. 乐在其中设计模式(C#) - 单例模式(Singleton Pattern)

    原文:乐在其中设计模式(C#) - 单例模式(Singleton Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 单例模式(Singleton Pattern) 作者:weba ...

  5. VS2015企业版本(安装包+key)

    VS2015中文企业版: http://pan.baidu.com/s/1eQtWvNs VS2015英文企业版: http://pan.baidu.com/s/1i3gZaVN —————————— ...

  6. 【C语言探索之旅】 第一部分第八课:第一个C语言小游戏

    ​ 内容简介 1.课程大纲 2.第一部分第八课:第一个C语言小游戏 3.第一部分第九课预告: 函数 课程大纲 我们的课程分为四大部分,每一个部分结束后都会有练习题,并会公布答案.还会带大家用C语言编写 ...

  7. html/css获得第一章

    1.基本教程来学习 大概3天课余时间阅读下面的两个教程. HTML文字教程 CSS文字教程 2.练习 看完教程后.做第一练习时,总结例如以下: 1)div居中 须要设置属性:margin-left:a ...

  8. Javascript J更深层次的理解avascript 基础知识

    eval全局函数 dojo loader会看到如下的功能    var eval_ = new Function('return eval(arguments[0]);'); //Function 函 ...

  9. A*寻路算法lua实现

    前言:并在相当长的时间没有写blog该,我觉得有点"颓废"该,最近认识到各种同行,也刚刚大学毕业,我认为他们是优秀的.认识到与自己的间隙,有点自愧不如.我没有写blog当然,部分原 ...

  10. nginx 提供静态内容

    Serving Static Content 提供静态内容 原文地址:http://nginx.com/resources/admin-guide/serving-static-content/ Th ...