第一个WindowService服务

背景:Web项目中需要定时执行一段程序

方法: 1.新建一个WindowService项目

    2.添加代码

public partial class Service1 : ServiceBase
    {
        System.Timers.Timer timer = null;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer = new System.Timers.Timer();
            timer.Elapsed += timer_Elapsed;
            timer.Interval = 10000;
            timer.Start();
        }
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }
            Console.WriteLine("Time elapsed");
        }

        protected override void OnStop()
        {
            if (timer != null)
            {
                timer.Stop();
            }
        }
    }

 

    3.添加安装程序

     

        3.1修改serviceProcessInstaller1属性中的account

      

            3.2 修改serviceInstaller1属性中的ServiceName(此名称为服务的名称)

                  4.添加外部工具

        

 

  

    5.运行

    

可以看到成功了

    6.删除服务 cmd.exe  

    sc delete "ServiceName"

posted @ 2017-07-30 21:09  半夏半心  阅读(497)  评论(1编辑  收藏  举报