Abbi
Abbi

Reputation: 597

Problem with two different timer variables in the same code firing at different intervals

Hi I have created a windows service and I have two different timer variables in there. 1st one fires off every 5 seconds and then does whats it is required to do. The second one fires every 30 seconds.

I make sure that when the function are getting executed I disable both the timers and enable once the function is complete.

My problem is my second longer (30 second ) timer never fires only the first one is firing. I had created this service 3 months ago and it was working fine till now. But now I do not see the timers work properly in a simple windows app i created to test their workings.

    timerLonger= New System.Timers.Timer()
    timerLonger.Interval = 30000
    timerLonger.Enabled = True

    timerShorter= New System.Timers.Timer()
    timerShorter.Interval = 5000
    timerShorter.Enabled = True

    AddHandler timerLonger.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf Process1)
    AddHandler timerShorter.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf Process2)

Sub Process1()
    timerLonger.Enabled = False
    timerShorter.Enabled = False
    DoProcessing1()
    timerShorter.Enabled = True
    timerLonger.Enabled = True
End Sub

Sub Process2()
    timerLonger.Enabled = False
    timerShorter.Enabled = False
    DoProcessing2()
    timerShorter.Enabled = True
    timerLonger.Enabled = True
End Sub

Upvotes: 1

Views: 244

Answers (2)

Hans Passant
Hans Passant

Reputation: 942040

You are exposing yourself to breakage due to unhandled exceptions. Unfortunately, the System.Timers.Timer class swallows exceptions without any diagnostic when it fires the Elapsed event. In your case, that will also leave the timer permanently disabled because the exception bypasses the statement that enables it again. Be sure to always use the Try/Catch/Finally keywords in your Elapsed event handler.

Or use the System.Threading.Timer class, it is a all-around better timer class. It doesn't swallow exceptions.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564671

When you disable then re-enable the longer timer, it resets its time. Since the shorter one fires 6 times as often, it never gets a chance to execute.

Instead of disabling the timers, if the goal is to prevent simultaneous operation of both timers, consider using some form of synchronization around your methods, such as a SyncLock.

Upvotes: 4

Related Questions