Jack-Leung

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如何创建Window Service                                      

    由于系统中有一个需求是当系统中任务中心有任务时,就通过一个windows service定时调用一个webservice将用户的待办任务通过ocs这个聊天工具发送给用户。所以最近的工作中接触到了windows service,这里就总结一下windows service是如何创建的。

在开始à运行àservices.msc就可以看到windows 服务了,或者控制面板à管理工具à服务,你也可以看到当前系统有那些服务了。 没错,接下来我们就要创建一个这样的服务,当你打开电脑后,就可以让这个服务启动去做些有用的事情。

打开vs20052003\2008开发工具,新建一个windows 服务项目OCSService,在这个项目里右键添加à新建项,首先我们需要添加一个windows 服务类 SendMessageToOcs.cs,一个安装程序类SendMessageToOcsInstall.cs,好,接下来我们谈谈如何实现这两个类。

Windows service 有个程序入口点就是Program.cs

using System.Collections.Generic;

using System.ServiceProcess;

using System.Text;

 

namespace OCSService

{

    static class Program

    {

        /// <summary>

        /// 应用程序的主入口点。

        /// </summary>

        static void  Main()

        {

            ServiceBase[] ServicesToRun;

 

            // 同一进程中可以运行多个用户服务。若要将

            // 另一个服务添加到此进程中,请更改下行以

            // 创建另一个服务对象。例如,

            //

            //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};

            //

            ServicesToRun = new ServiceBase[] { new SendMessageToOcs() };

 

            ServiceBase.Run(ServicesToRun);

        }

    }

}

  ServicesToRun = new ServiceBase[] { new SendMessageToOcs() };这行代码可能需要更改一下你NEW的那个windows service

 

创建的windows service的实现

partial class SendMessageToOcs : ServiceBase

    {

        private com.lab.ocs.CMPService ocs= new OCSService.com.lab.ocs.CMPService();//调用发送消息给ocs的webservice

        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DbConnectionString"].ToString());

        DataSet ds = new DataSet();

        public SendMessageToOcs()

        {

            InitializeComponent();

            System.Timers.Timer time = new System.Timers.Timer();

            int seconds = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["Intervals"].ToString());//时间周期存放在webconfig中

            time.Interval = seconds;//每个多少毫秒后给ocs发信息

            time.AutoReset = true;

            time.Enabled = true;

            time.Elapsed+=new System.Timers.ElapsedEventHandler(time_Elapsed);

//定时触发一个事件如果不是定时触发,而是时刻都在运行可以使用protected override void //OnStart(string[] args),和protected override void OnStop()两个方法表示服务启动和结束事件

            time.Start();

         

        }

  /// <summary>

        /// 每隔一段时间后,就给用户发信息

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private  void time_Elapsed(object sender, ElapsedEventArgs e)

        {

            try

            {

                DataTable dtUsers = new DataTable();

                dtUsers = this.GetUserlist();//获取所有用户

                if (dtUsers.Rows.Count != 0)

                {

                    int count = dtUsers.Rows.Count;

                    DataView dvToDos = new DataView();

                    DataView dvEletter = new DataView();

                    DataView dvPublicFile = new DataView();

                    DataView dvTotal = new DataView();

                    for (int k = 0; k < count; k++)

                    {

                        //取得此人所有的待办任务

                        ds.Tables.Clear();//先将里面的table清除

                        string userName = dtUsers.Rows[k]["name"].ToString();

                        string uid = dtUsers.Rows[k]["uid"].ToString();//比如admin

                        int id = int.Parse(dtUsers.Rows[k]["id"].ToString());//比如6 

                        dvToDos = this.GetToDoList(id);//获取待办任务

 

 

                        dvEletter = this.GetEletterList(id);//电子函件

                        dvPublicFile = this.GetPublicFile(id);//公文传阅

                        dvTotal = this.UnionDV(dvToDos, dvEletter, dvPublicFile);//合并数据

                        if (dvTotal.Count > 0)

                        {

                            int m = dvTotal.Count;

                            System.Text.StringBuilder messages = new StringBuilder(String.Empty);

                            messages.Append(userName + ",您好,您有如下待办理任务:");

                            for (int n = 0; n < m; n++)

                            {

                                messages.Append(Convert.ToString(n + 1) + "、【" + dvTotal[n]["name"] + "】有" + dvTotal[n]["TaskNum"].ToString() + "个待办理任务    ");

                            }

                            ocs.AddMessage(uid, messages.ToString());//调用webservice将每个人的代办任务消息发送给相关用户

                        }

                        //释放资源

                        for (int p = 0; p < dvEletter.Count; p++)

                        {

                            dvEletter.Delete(p);

 

 

                        }

                        for (int s = 0; s < dvToDos.Count; s++)

                        {

                            dvToDos.Delete(s);

 

 

                        }

                        for (int o = 0; o < dvPublicFile.Count; o++)

                        {

                            dvPublicFile.Delete(o);

                        }

                        for (int q = 0; q < dvTotal.Count; q++)

                        {

                            dvTotal.Delete(q);

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw new Exception(ex.Message);

            }

           

        }

 

这个windows service主要是这些东西了,具体另外一些代码就不写出来了,然后还有SendMessageToOcsInstall.cs,这个类是必须的需要使用它来将服务注册到计算机,这个类的实现如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Configuration.Install;

using System.ServiceProcess;

 

 

namespace OCSService

{

    [RunInstaller(true)]

    public partial class SendMessageToOcsInstall : Installer

    {

        private ServiceInstaller install;

        private ServiceProcessInstaller processInstall;

        public SendMessageToOcsInstall()

        {

            InitializeComponent();

            install = new ServiceInstaller();

            processInstall = new ServiceProcessInstaller();

            install.StartType = ServiceStartMode.Automatic;

            processInstall.Account = ServiceAccount.LocalSystem;

            install.ServiceName = "SendMessageToOcs";

            install.Description = "定时发送提醒消息到OCS,此服务的目的是当办公系统中有代办理任务时,定时将任务发送到ocs工具上,这样有个催办的作用";

            this.Installers.Add(install);

            this.Installers.Add(processInstall);

            //或使用添加集合的方法

            //this.Installers.AddRange(new System.Configuration.Install.Installer[]{install,processInstall});

        }

    }

}

 

 

然后编译下这个项目就算结束了,生成成功以后,需要在命令行注册一下,

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil OCSService.exe

取消注册

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil -u OCSService.exe

可以将以上两行代码放在一个cmd或bat类型的文件里,这样双击就可以了。

注册后你再进入服务就可以看到刚才创建的服务了

posted on 2011-05-20 10:27  Jack.leung  阅读(1013)  评论(0编辑  收藏  举报