C#写windows服务实例

因为需要每天定时(晚上九点)把数据插入到数据库中,所以决定写成一个windos 服务。

 

参考文档:http://dev.firnow.com/course/4_webprogram/asp.net/asp_netshl/2008414/110334.html

 

1。在VS2008创建windows service工程

文件---新建---项目----windows服务,名称AdioService

 

2。结构如下图所示,双击service1.cs,在onstart中写具体代码,注意如果代码执行需要很长时间,则需要将方法放在子线程中,否则windows服务会启动不起来。

3。定时器timer的使用

拖一个timer,必须为system.Timers.Timer,设置参数。Interval为计时器启动的时间间隔。

双击timer,在方法体中写入要间隔执行的代码。

定时启动的话

 protected override void OnStart(string[] args)
        {
            // 取系统当前时间
            DateTime now = DateTime.Now;
            // 判断当前时间是否为21点

            if (now.Hour >= 21)
            {
                thread1 = new Thread(new ThreadStart(InsertToSQL));//用子线程执行方法InstertSQL             

                thread1.Start();
               }

          }

 

 

 private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) //双击timer,定时执行方法
        {
            InsertToSQL();
        }

4。添加安装程序

在AdioService.cs[设计]右键---添加安装程序,会出现

注意:account选择localhost  ;StartType选择Automatic(开机自动执行)

5。安装服务

开始-运行-cmd
cd C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727

 

找到debug下的.exe,复制路径(例如 C:/Documents and Settings/Administrator/桌面/Audiomonitor/d1/AudioService/bin/Debug/AudioService.exe")

 

安装命令

InstallUtil  "C:/Documents and Settings/Administrator/桌面/Audiomonitor/d/AudioService/bin/Debug/AudioService.exe"

卸载命令

InstallUtil  /u "C:/Documents and Settings/Administrator/桌面/Audiomonitor/d1/AudioService/bin/Debug/AudioService.exe"

在控制面板---管理工具-----服务----右键----启动服务

 

6。异常情况

如果不能正常启动服务,说明服务有错误。可以利用“日志查看器”查看错误信息。(调试比较麻烦)。

注意每次对服务改动的话,都必须重新安装。

 

7。想要服务在遇到异常停止后自动重启

 

找到  服务-----右键----属性---恢复-----重新启动服务

posted on 2010-05-25 09:26  学中医的程序员  阅读(201)  评论(0编辑  收藏  举报

导航