Windows service with timer

前端 未结 3 1540
迷失自我
迷失自我 2020-11-27 05:18

I have created a windows service with timer in c#.net. it works fine while i debug/build the project in visual studio but it does not perform its operation after installatio

3条回答
  •  孤城傲影
    2020-11-27 05:40

    First approach with Windows Service is not easy..

    A long time ago, I wrote a C# service.

    This is the logic of the Service class (tested, works fine):

    namespace MyServiceApp
    {
        public class MyService : ServiceBase
        {
            private System.Timers.Timer timer;
    
            protected override void OnStart(string[] args)
            {
                this.timer = new System.Timers.Timer(30000D);  // 30000 milliseconds = 30 seconds
                this.timer.AutoReset = true;
                this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
                this.timer.Start();
            }
    
            protected override void OnStop()
            {
                this.timer.Stop();
                this.timer = null;
            }
    
            private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                MyServiceApp.ServiceWork.Main(); // my separate static method for do work
            }
    
            public MyService()
            {
                this.ServiceName = "MyService";
            }
    
            // service entry point
            static void Main()
            {
                System.ServiceProcess.ServiceBase.Run(new MyService());
            }
        }
    }
    

    I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.

    Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.

    Hope this helps!

提交回复
热议问题