Nick3
Nick3

Reputation: 639

Timer not fireing on interval

I have a problem that min timer event is not fired when it should be, I set it to an interval of 500ms, but as I can see in my logg, this doesn't work as intended. I want the code to excecute when wait 0.5 seconds then start executing again!

    public void initilize_Rfid()
    {
        _timerComm = new System.Timers.Timer(500);
        _timerComm.Elapsed += CommTimerEvent;
        _timerComm.Enabled = true;
    }

    private void CommTimerEvent(object source, ElapsedEventArgs e)
    {
        try
        {
            _timerComm.Enabled = false;
            Logg("Inside CommTimerEvent " + _name);

            //TALKING TO A SERIALPORT AND DETERMENATING IF TO CONTINUE WITH THE TIMER

            if ((_continueTimer)
            {
                _timerComm.Enabled = true;
               Logg("Re-activating timer " + _name);
            }
        }
        catch (Exception ex) { Logg(ex.ToString()); }
    }

I can see the text "Inisde ComTimerEvent TEST1", and then about 0.8 seconds later I get my "Re-activating timer TEST1". That is all just fine. But after this I get a up to 3 seconds delay until the timer fires again... Can I prevent this in some way?

Upvotes: 1

Views: 245

Answers (2)

Anees Deen
Anees Deen

Reputation: 1403

Instead you can Use DispatcherTimer. The following code will help you to fire a method for every 5 seconds.

DispatcherTimer LabelTimer = new DispatcherTimer();
                        LabelTimer.Interval = TimeSpan.FromSeconds(5);
                        LabelTimer.Tick += new EventHandler(TaskTimer_Tick_THROW);

Upvotes: 1

Alexandre Machado
Alexandre Machado

Reputation: 587

You're missing :

 _timerComm.Start();

this will start the timer. If you put it like this:

public void initilize_Rfid()
{
    _timerComm = new System.Timers.Timer(500);
    _timerComm.Elapsed += CommTimerEvent;
    _timerComm.Enabled = true;
    _timerComm.Start();
}

your code should work if you call this method.

Upvotes: 1

Related Questions