Set the counter value on Timer.Interval

626 views Asked by At

I have a timer which I am using to execute an event in the method. I need to run it every 5 minutes but need to change the counter value when the timer ticks at t 10 minutes but then again reset the counter.

So, when the timer execution is past 5,15 or 25 minutes I need to set counter value to 1. While on 10, 20 or 30 minutes interval I need to set it to 2. So, in short the default counter value will be always 2 while when the execution time is a multiple of 10 & then again reset to default again.

How should I do that on System.Timers?

Here's what I have so far:

using System.Timers;

namespace Demo
{
    public class SampleWorker
    {
        private Timer timer = new System.Timers.Timer();
        private bool _timerInUse = false;
        private double _timerFrequency = 300000;
        private int _counter = 1;


        public void Main()
        {
            StartTimer();
        }

        private async void StartTimer()
        {
            try
            {
                timer.Elapsed += new ElapsedEventHandler(this.TriggerEvent);
                timer.Interval = _timerFrequency; //5 mins
                timer.Enabled = true;
                // when timer runs with units as 5 set _counter to 2 else keep 1
            }
            catch (Exception ex)
            {
                //log exception
            }

        }

        private async void TriggerEvent(object source, ElapsedEventArgs e)
        {
            if (_timerInUse == false)
            {
                _timerInUse = true;
                try
                {
                    Foo(_counter);
                }
                catch (Exception ex)
                {
                   //log exception

                }
                _timerInUse = false;
            }
        }
    }
}
0

There are 0 answers