Rahul Hendawe
Rahul Hendawe

Reputation: 912

timer_Elapsed() Event not firing

I am using Timer in Windows Service on OnStart() method handling timer_Elapsed() event check after every 5 min.

But timer_Elapsed() not firing/calling after 5 min, Please correct me If I am doing anything wrong in below code.

        protected override void OnStart(string[] args)
        {
            try
            {
                genLogs.WriteErrorLog("Service Started OnStart.");
                //int tmStart = Convert.ToInt32(ConfigurationManager.AppSettings["tim"]);
                using (Timer timer = new Timer(30000))  //  (1000 * 5 * 60) for 5 minutes
                {
                    timer.Elapsed += timer_Elapsed;
                    timer.Start();
                    //Console.WriteLine("Timer is started");
                    genLogs.WriteErrorLog("Timer is started.");
                    //Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
            }

        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                genLogs.WriteErrorLog("Service Started Checking Windows Services and Web AppPools.");

                serviceLogic.InsertStatus();

                genLogs.WriteErrorLog("Service Calls Send SendEmails Method.");
                serviceLogic.SendInfo();
            }
            catch (Exception ex)
            {
                genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
            }
        }

Upvotes: 0

Views: 1253

Answers (2)

Andreas Fredriksson
Andreas Fredriksson

Reputation: 161

I think it might be because you are doing it in a using block.

using (Timer timer = new Timer(30000))  //  (1000 * 5 * 60) for 5 minutes
            {
                timer.Elapsed += timer_Elapsed;
                timer.Start();
                //Console.WriteLine("Timer is started");
                genLogs.WriteErrorLog("Timer is started.");
                //Console.ReadLine();
            } <- Your timer stops existing here

Doing it in a using block would be the same as saying timer.Dispose(); which disposes the timer and therefore it can't call any methods. This should work:

Timer timer = new Timer(30000)
timer.Elapsed += timer_Elapsed;
timer.Start();

Upvotes: 3

Andrey Bobrov
Andrey Bobrov

Reputation: 201

disposing your timer makes it impossible to run the callback.

in case you wish to dispose it, you must synchronize that call.

Check this post -> How do I gracefully stop a System.Threading.Timer?

Upvotes: 2

Related Questions