Two timers running simultaneously and independently

15,790
Public Class Form1
    'a timer that fires periodically
    Dim WithEvents aTimer As New System.Threading.Timer(AddressOf TickTock, Nothing, 0, 500)
    'a stopwatch for each event
    Dim swEV1 As New Stopwatch
    Dim swEV2 As New Stopwatch
    'how long between executions
    Dim ev1Time As New TimeSpan(0, 0, 1)
    Dim ev2Time As New TimeSpan(0, 0, 5)

    'test
    Private Sub Button1_Click(sender As System.Object, _
                              e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        'start the test
        swEV1.Start()
        swEV2.Start()
    End Sub

    Dim ev1 As New Threading.Thread(AddressOf event1)
    Dim ev2 As New Threading.Thread(AddressOf event2)

    Private Sub TickTock(state As Object)
        If swEV1.IsRunning Then
            'check the elapsed time and run the thread when needed
            'only one thread per event is allowed to run
            If swEV1.Elapsed >= ev1Time Then
                If Not ev1.IsAlive Then
                    swEV1.Reset() 'reset the stopwatch
                    swEV1.Start()
                    ev1 = New Threading.Thread(AddressOf event1)
                    ev1.IsBackground = True
                    ev1.Start()
                End If
            End If

            If swEV2.Elapsed >= ev2Time Then
                If Not ev2.IsAlive Then
                    swEV2.Reset()
                    swEV2.Start()
                    ev2 = New Threading.Thread(AddressOf event2)
                    ev2.IsBackground = True
                    ev2.Start()
                End If
            End If

        End If
    End Sub

    Private Sub event1()
        Debug.WriteLine("EV1 " & DateTime.Now.ToString)
        Threading.Thread.Sleep(500) 'simulate work
    End Sub

    Private Sub event2()
        Debug.WriteLine("EV2 " & DateTime.Now.ToString)
        Threading.Thread.Sleep(3000) 'simulate work
    End Sub


End Class
Share:
15,790
Nefariis
Author by

Nefariis

Pragmatic developer and data enthusiast - I specialize in all things automation. I write in Python, Kotlin, JAVA, Typescript, Regex, and SQL to create custom applications that support the teams around me. For fun I wrestle alligators, battle rap in NY subways, and Netflix and chill with Tony Danza. Achievements: I've seen the internet in its entirety, my record is 14 marshmallows in chubby bunny, and - I know a girl.

Updated on June 04, 2022

Comments

  • Nefariis
    Nefariis almost 2 years

    First of all, I just wanted to say thanks for all the help given in the past couple weeks. I've learned a ton and my program has been saving me hours and hours of work every day.

    I want to expand it a little bit and add a second timer that runs parallel to the first timer, but is not affected in any way shape or form by the first timer.

    I've tried nesting the second loop in the first loop but the second loop takes 3 seconds to complete (I use thread.sleep(3000)), so I found that it froze the first loop till the second loop finishes. I was reading about system threading (System.Timers.Timer) and it seems like that is the route I want to go.

    I wrote this quick as an example:

    This assumes that I added a windows timer control as timer1

    Option Strict On
    Imports System
    Imports System.Timers
    
    Public Class form1
    
      Private Shared timer2 As System.Timers.Timer
      timer2 = New System.Timers.Timer
      AddHandler timer2.Elapsed, AddressOf OnTimedEvent
    
      Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                               Handles Button1.Click
        timer1.Interval = 1000
        timer1.enabled = true
        timer2.Interval = 5000
        timer2.Enabled = True
      End sub
    
      Public Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                             Handles Timer1.Tick
      'code for timer1 here
      End Sub
    
      Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        'code for timer2 here
      End Sub
    
    End Class 
    

    Does this even make sense?... and again I can't use the timer1 to set off the second round of events because of the thread.sleep. I was hoping that the code above puts the second thread to sleep while the windows.form.timer continues on ticking every 1000 ms