Windows Service的建立和安装调试以及定时器的用法

1、打开Visual Studio 2008,新建一个Windows Service项目:MyFirstService。

 

 

2、单击设计器窗口(只有一个Service1),在属性窗口里修改ServiceName属性和(Name)属性为:FirstService,AutoLog为True。
(如果不单击设计器窗口,那么在属性窗口中显示的将会是Solution属性)。

 

修改完毕后,程序代码里的文件名称已经改过来,但是在Solution里和设计器标签上,还会显示Service1,不必在意。

 

 

3、在Solution里双击Program.cs,可以看到其中Main 方法已经创建了“FirstService”的实例。

 

 

4、在设计器窗口点击“click here to switch to code view”,打开代码窗口。可以看到我们当初给的项目名称变成了命名空间,而Service名称变成了类(class)。默认里面有一个构造函数和开始(OnStart)、结束(OnStop)事件。这就是一个Windows Service的基本结构。

 

 

 

5、把自定义事件日志添加到 Windows 服务中。

 

a)在设计器窗口点击Service1.cs[Design],然后从工具箱Components组里拖一个EventLog控件:eventLog1。

b)在构造函数里定义一个用户事件日志:FirstLog
在本地计算机上创建一个自定义日志的语法为:

System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "LogName");

 

建立日志之前还要先判断它是否已经存在:

    if (!System.Diagnostics.EventLog.SourceExists("MySource"))
    {        
            System.Diagnostics.EventLog.CreateEventSource("MySource","FirstLog");
    }
    eventLog1.Source = "MySource";
    eventLog1.Log = "FirstLog";

 

 

c)在OnStart和OnStop方法里加入写内容到日志里的命令。还可以重写 OnPause、OnContinue 和 OnShutdown 方法来定义对组件的进一步处理。

 

6、为服务创建安装程序
a)切换到设计视图,右击空白处,选择Add Installer。项目中新增了一个名为ProjectInstaller的组件类,里边包含两个安装程序:服务的安装程序和服务关联进程的安装程序。

 

 


b)将serviceInstaller1的StartType属性设置为Automatic,将serviceProcessInstaller1的Account属性设为LocalService(这不能读写日志,需改成LocalSystem)。


c)右击项目名称,选择Properties,在Application页面里设置Startup object为MyFirstService.Program。


d)按Ctrl+Shift+B,生成服务项目。

 

 

7、为服务创建安装项目--右击解决放案,添加新建项目。

 

 

8、向安装项目添加 MyFirstService.exe
右键单击MyFirstServiceSetup,Add->Project Output,在出现的对话框里,选择Primary Output。

 

 

9、向安装项目添加自定义操作

右键单击MyFirstServiceSetup,View->Custom Actions。

 

右键单击Custom Actions栏目,选择Add Custom Actions,

 

 

再选择“Application Folder”里面的“Primary output from MyFirstService (Active)”,确定。

 

 

10、安装 Windows 服务 -- 右键单击MyFirstServiceSetup,Build,然后再Install

 

 

11、启动和停止服务
右键单击My Computer,选择Manage->Services and Applications->Service,找到里边的FirstService,右键单击,可选择Start或Stop。
(也可以使用Ctrl+Alt+Delete的方式启动和停止服务)。

 

 

12、查看日志
右键单击My Computer,选择Manage->System Tools->EventViewers->Applications and Services Logs,就能看到FirstLog。

 

 

13、修改程序重新安装
实际上,这样的程序运行时提示说,没有程序调用这个服务,它自动停止了。后来加上一个定时器,Enabled=True,然后(a)停止服务,(b)重新编译项目,(c)重新编译安装项目,(d)再安装就可以了。

 

14、定时器的用法
上面是我在工具箱中拖了一个timer控件,但无论是在设计时设置Enabled=True,还是在OnStart里设置Enabled=True,都不起作用,timer1_Tick()没有被执行。

 

后来经过搜索找到Timer Class,实现了定时的功能。

a)需要引入System.Timers.Timer命名空间。
b)在class里定义变量:private static System.Timers.Timer aTimer;
c)在OnStart里初始化,并引用委托实现定时。
d)定时事件

 

15、参考链接:

演练:在组件设计器中创建 Windows 服务应用程序
http://msdn.microsoft.com/zh-cn/library/zt39148a(v=VS.80).aspx

Timer Class
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

ElapsedEventHandler Delegate
http://msdn.microsoft.com/en-us/library/system.timers.elapsedeventhandler.aspx

 

请教一个Window Service入门问题

http://topic.csdn.net/u/20100924/00/b892ac33-b98b-47ab-a4c7-3c4d75a2fe37.html

 

Windows Service中的定时问题

http://topic.csdn.net/u/20101007/02/932751db-93e0-48cb-97b4-78ccb39f6f23.html?1441444801

 

C# Timer用法及实例详解
http://developer.51cto.com/art/200909/149829.htm 

 

 

 

16、程序清单如下(其中timer1部分为定时器控件,不好用):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;

namespace MyFirstService
{
    public partial class FirstService : ServiceBase
    {
        private static System.Timers.Timer aTimer;

        public FirstService()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("MyFirstSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource("MyFirstSource", "FirstLog");
            }
            eventLog1.Source = "MyFirstSource";
            eventLog1.Log = "FirstLog";
        }

        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In onStart.");
            this.timer1.Enabled = true;

            // Create a timer with a ten second interval.
            aTimer = new System.Timers.Timer(10000);

            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

            // Set the Interval to 2 seconds (2000 milliseconds).
            aTimer.Interval = 2000;
            aTimer.Enabled = true;

        }

        protected override void OnStop()
        {
            eventLog1.WriteEntry("In onStop.");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string tick = DateTime.Now.ToString();
            eventLog1.WriteEntry("timer tick:"+tick);
        }
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            string time = DateTime.Now.ToString();
            eventLog1.WriteEntry("This is: "+time);
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值