zoukankan      html  css  js  c++  java
  • WindowsService创建和安装

           Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合。它没有用户界面,并且也不会产生任何可视输出。任何用户消息都会被写进Windows事件日志。计算机启动时,服务会自动开始运行。它们不要用户一定登录才运行,它们能在包括这个系统内的任何用户环境下运行。通过服务控 制管理器,Windows服务是可控的,可以终止、暂停及当需要时启动。最近项目中有这么一个需求,客户可以定时向服务器发送MQ实现特定业务操作。

          让我们一起进入WinService的学习之旅吧~

          .net创建Windows服务非常简单,创建一个项目,从面板中选择项目的类型为Windows服务,修改服务的名字为MyService,创建好的项目如图所示:

          MyService继承自系统类System.ServiceProcess.ServiceBase,其中包含两个方法,OnStart(启动服务执行方法)和OnStop(停止服务执行方法)两个方法,查看MyService的代码如图所示:

    Windows服务的启动程序入口=>Program.cs:

         如果要启动多个服务,可以向ServicesToRun数组中增加多个Windows服务,比如新增Service2,Service3:

    View Code
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new MyService() ,
                                    new Service2(),
                                    new Service3()
                };
                ServiceBase.Run(ServicesToRun);

         接着可以自定义服务执行的业务逻辑,本服务模拟场景:每隔10分钟,从数据库获取现在时间到未来10分钟这段时间内,需要处理的某种业务(为了简单化=》向指定地址写入字符串和当前时间),业务逻辑代码如下所示:   

    View Code
    namespace WinserviceDemo
    {
        public partial class MyService : ServiceBase
        {
            public MyService()
            {
                InitializeComponent();
            }
    
            System.Timers.Timer timer1 = null;
            System.Timers.Timer timer2 = null;
            public List<DateTime> list = new List<DateTime>();
            public DateTime nowTime;
    
            protected override void OnStart(string[] args)
            {
                timer1 = new System.Timers.Timer();
                timer1.Start();
                timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                timer1.Interval = 1000 * 60;//每隔一分钟
    
                //timer2模拟了从数据库获取用户需要定时执行的操作时间点(此时间点
                //与本服务无耦合关系)
                timer2 = new System.Timers.Timer();
                timer2.Start();
                timer2.Elapsed += new System.Timers.ElapsedEventHandler(timer2_Elapsed);
                timer2.Interval = 1000 * 60 * 10;//每隔十分钟
            }
    
            public void timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {//模拟从数据库获取数据,并且只获取当前时间到未来的10min段的数据
                list.Clear();
                list.Add(DateTime.Now.AddMinutes(9));
                list.Add(DateTime.Now.AddMinutes(6));
                list.Add(DateTime.Now.AddMinutes(4));
                list.Add(DateTime.Now.AddMinutes(2));
    
                list.Sort((x, y) => x.CompareTo(y));
            }
    
            public void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                if (list.Count>0)
                {
                    nowTime = DateTime.Now;
                    if (list[0].Minute<=nowTime.Minute)
                    {
                        list.Remove(list[0]);
                        writeFile();
                    }
                }
            }
    
            private void writeFile()
            {
                string filePath = "D:\\WinService\\test.txt";
                StreamWriter sWrite = null;
                if (!File.Exists(filePath))
                {
                    sWrite = File.CreateText(filePath);
                }
                else
                {
                    sWrite = File.AppendText(filePath);
                }
                sWrite.WriteLine("写入时间:" + DateTime.Now.ToString("yyyyMMdd HHmmss"));
                sWrite.Flush();
                sWrite.Close();
            }
    
            protected override void OnStop()
            {
                //
            }    
        }
    }

         编译通过后,开始部署安装程序:

    1、将写好的Windows服务()切换到设计视图,右键》添加安装程序;

    2、切换到新添加的 添加安装程序()的设计视图(包含两个:serviceInstaller1和serviceProcessInstaller1),设置serviceProcessInstaller1属性Account为LocalSystem;serviceInstaller1的属性ServiceName:MyService(服务的名字),StartType:Automatic(设置系统启动时服务自动启动)。

         ServiceAccount是枚举类型,MSDN这样描述:http://msdn.microsoft.com/zh-cn/library/system.serviceprocess.serviceaccount(v=vs.80).aspx(包括使用示例)

        

    3、接着新建一个安装项目(为当前服务添加安装项目),安装项目取名为MyServiceSetUp:

    4、右键点击MyServiceSetUp=》添加=》项目输出,在弹出界面设置主项目输出为WinserviceDemo,点击确定;

    5、右键》视图》自定义操作》安装(右键)》添加自定义操作》打开应用程序文件夹》选择上一步设置的主输出》确定;

    6、右键》视图》自定义操作》卸载(右键)》添加自定义操作》打开应用程序文件夹》选择上一步设置的主输出》确定;

    7、重新生成,在安装项目的Debug或Release问价加下可以找到安装程序,包含了所有的类库、组件,直接双击即可安装服务。

    8、完成安装后,即可直接在服务管理器(右键我的电脑》管理》服务和应用程序》服务)中找到MyService服务,启动即可。

  • 相关阅读:
    MSDN Magazine搞错了
    Visual Studio 2005中设置调试符号(Debug Symbols)
    BCB 6的问题
    吴裕雄天生自然Spring Boot使用Spring Data JPA实现人与身份证的一对一关系映射
    吴裕雄天生自然Spring BootSpring Data JPA
    吴裕雄天生自然Spring BootSpring Boot对JSP的支持
    吴裕雄天生自然Spring BootSpring Boot的异常统一处理
    吴裕雄天生自然Spring Boot使用Spring Data JPA实现Author与Article的一对多关系映射
    吴裕雄天生自然Spring Boot解决 Error creating bean with name 'entityManagerFactory' defined in class path resource
    吴裕雄天生自然Spring Boot@ExceptionHandler注解和@ControllerAdvice注解
  • 原文地址:https://www.cnblogs.com/yangyp/p/3013184.html
Copyright © 2011-2022 走看看