ElapsedEventHandler is not fired in Windows Service

1.1k Views Asked by At

I have pretty simple window service which I developed after following this tutorial : http://www.c-sharpcorner.com/UploadFile/naresh.avari/develop-and-install-a-windows-service-in-C-Sharp/

However I notice that ElapsedEventHandler was never fired unlike tutorial:

  public partial class Scheduler : ServiceBase
    {
        public Timer timer1 = null;
        public Scheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            timer1 = new Timer();
            this.timer1.Interval = 30000;
            this.timer1.Elapsed+=new ElapsedEventHandler(this.timer1_Tick);
            Library.WriteErrorLog("Test Window service started");

        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("test window service stopped");
        }

        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            Library.WriteErrorLog("Timer ticked and some job has been done successfully");
        }
    }
1

There are 1 best solutions below

1
On BEST ANSWER

You have to enable the timer. See here for an example. The article you refer to also does it.

timer1.Enabled = true;