第一个WindowService服务

Posted 半夏半心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第一个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"

以上是关于第一个WindowService服务的主要内容,如果未能解决你的问题,请参考以下文章

asp.netcore在windowservice中开放端口

XpsDocumenWriter从Windows服务挂起,但从控制台运行时工作正常

streambase service 变为 window service启动

片段不起作用并且有错误

C# Window Service 不调用定时器函数

由于休息api延迟,视图寻呼机中的第一个片段未显示