Results 1 to 11 of 11

Thread: [RESOLVED] Two timers running parallel to each other...

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Sep 2011
    Location
    Seattle
    Posts
    218

    Resolved [RESOLVED] Two timers running parallel to each other...

    Hey guys, first of all I just wanted to say thanks for all the help given in the past couple weeks. Ive 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 want the timers to run like this:

    Time Timer1 Timer2
    0 X X
    1 X
    2 X
    3 X
    4 X
    5 X X
    6 X
    7 X
    8 X
    9 X
    10 X X


    Ive tried nesting the second loop in the first loop but the second loop takes 3 seconds to complete, 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

    vb Code:
    1. Option Strict On
    2. Imports System
    3. Imports System.Timers
    4.  
    5. public class form1
    6.  
    7.     Private Shared timer2 As System.Timers.Timer
    8.         timer2 = New System.Timers.Timer
    9.         AddHandler timer2.Elapsed, AddressOf OnTimedEvent
    10.        
    11.  
    12.     Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    13.  
    14. timer1.Interval = 1000
    15. timer1.enabled = true
    16. timer2.Interval = 5000
    17. timer2.Enabled = True
    18.  
    19. End sub
    20.  
    21. Public Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    22.  
    23. 'code for timer1 here
    24.  
    25. end sub
    26.  
    27.     Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
    28.  
    29.         'code for timer2 here
    30.  
    31.     end sub
    32.  
    33. end class


    Does this even make sense... or did I just spend the last 20 minutes making up my own language?

  2. #2
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Two timers running parallel to each other...

    You don't need a second timer in your case.
    You need only one timer. The actions that should take place on the second timer's events occur in every 5 ticks of the first timer, right? Then add a static integer variable to the first timer event and make it increment with each tick:

    vb Code:
    1. Static tickspassed As Integer = 0
    2. tickspassed += 1

    then just check:

    vb Code:
    1. If tickspassed = 4 Then
    2.    tickspassed = 0
    3.    ' Do what must be done here
    4. End If

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Sep 2011
    Location
    Seattle
    Posts
    218

    Re: Two timers running parallel to each other...

    I see what you are saying, but if the process that runs every 5 ticks (E2), takes three ticks to complete, then wouldnt the program fire like this:


    T|E1|E2
    0|X|X
    1|
    2|
    3|X
    4|X
    5|X|X
    6|
    7|
    8|X
    9|X
    10|X|X
    11|
    12|
    13|X
    14|X
    15|X|X


    As both events are running on the same thread? Essentially Event2 puts the program to sleep (sorry if I didnt mention this before) for 3 seconds, which if I understand form.timers would stop Event1 from firing until Event2 would be done from being asleep and unfreeze the program

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Two timers running parallel to each other...

    It wouldn't stop it from firing, but it would stop the tick event from being handled because the process is blocking all pumping of the message queue. One solution might be to add some appropriate Application.DoEvents such that the messages do get pumped, but if your process is really taking 3s to complete, I wouldn't do that. What happens if that process runs a bit long and takes 5s, and you have DoEvents in there? Might it not start right into processing it a second time without finishing the first time? I'm not sure, but it seems likely.

    That long running process sounds like a prime candidate to be moved to a different thread. What is it doing?
    My usual boring signature: Nothing

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Sep 2011
    Location
    Seattle
    Posts
    218

    Re: Two timers running parallel to each other...

    I have no doevents in my application, from everything I have been reading, it sounds like I should try to avoid them as a beginner coder.

    The process could very well take longer then 3 seconds, thats why I was planning on giving it a 5 second sleep timer. Which is why I had ever intention on starting another thread.

    Does that first bit of code I posted, the System.Timers.Timer, not start another thread?

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Sep 2011
    Location
    Seattle
    Posts
    218

    Re: Two timers running parallel to each other...

    Also, I have had these two errors since I have started my project:

    "A reference was created to embedded interop assembly 'stdole' because of an indirect reference to that assembly from assembly 'AxInterop.MSComctlLib'. Consider changing the 'Embed Interop Types' property on either assembly."

    and

    "A reference was created to embedded interop assembly 'stdole' because of an indirect reference to that assembly from assembly 'mscomctl'. Consider changing the 'Embed Interop Types' property on either assembly."

    Then just a second ago, I started getting this error and now I cant publish the program.

    "The referenced assembly "Microsoft.VisualBasic.PowerPacks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" could not be resolved because it has a dependency on "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project."

    Im not using power pack or mscomctl, the only things I am importing are:

    System.Windows.Forms.DataVisualization.Charting
    System.IO
    System.Text.RegularExpressions
    Microsoft.Office.Interop.Excel

    I appreciate the help with the timer threading but if I could also get some advice on this it would be greatly appreciated.

  7. #7
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,754

    Re: Two timers running parallel to each other...

    It is not clear what you are trying to do, but maybe this will help:

    Code:
    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
    Create a new project with one button, copy / paste code. Run it and press the button.
    Last edited by dbasnett; Oct 28th, 2011 at 06:44 AM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Two timers running parallel to each other...

    Why are you working with MSComctl? Wasn't that about the common dialogs (save, open, and so forth)? If so, there are .NET alternatives that should get rid of that issue.
    My usual boring signature: Nothing

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Sep 2011
    Location
    Seattle
    Posts
    218

    Re: Two timers running parallel to each other...

    @dbasnett... Does this script effectively open two threads that run simultaneously without waiting for each other. It seems that EV2 would still cause EV1 to wait 3000 ms.

    @Shaggy Hiker... Im not using MSComCtl or Power Packs. I cant figure out where the program is refrencing them from. I didnt find anything in the recently added refrences, and I havent found any mention of them in the program properties>refrences either. I just cant figure out how to shake these warnings and then all of a sudden my program stopped publishing.

    Let me preface this next part by saying that Im not disregarding any code/help that has been offered thus far - but, for my own educational purposes can someone comment on the code that I first published above and tell me if it makes sense or not; or if it might, in practice, work. It seemed like it would logically work in my head, I just havent recived any feeback for it. With that being said I am looking into Dbasnett's option right now.

    Thanks Guys

  10. #10
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,754

    Re: Two timers running parallel to each other...

    "@dbasnett... Does this script effectively open two threads that run simultaneously without waiting for each other. It seems that EV2 would still cause EV1 to wait 3000 ms."

    It depends on what is going on inside of the events(hint), and how many processors (cores) the code is executing on. Try it and see.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Sep 2011
    Location
    Seattle
    Posts
    218

    Re: Two timers running parallel to each other...

    took me a few days to integrate it but I finally got it dbasnett. Thank You.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width