locked
Use of timer and setting timer in code RRS feed

Answers

  • Hi,

     There are several examples and tutorials on the net for using a Timer. Take a look at the link below.   8)

    Example of the timer control in VB.net

     

     Here is the msdn link to the Timer class that you can use to learn a little about the Methods, Properties, and Events of a Timer.

    Timer Class


    If you say it can`t be done then i`ll try it

    Saturday, October 4, 2014 12:58 PM
  • There are several types of timer and there are many things you might want to do with a timer. Here is a simple example.

    • Create a Windows forms project.
    • In the forms designer, drag a Timer onto the form from the Components section of the toolbox.
    • Change the timer's name property to MyTimer.
    • Double-click on the timer in the designer. You will be taken to the code window and a Click Event handler will be created.
    • Change the forms class to look like this.
    Option Strict On
    Option Explicit On
    
    Public Class Form1
    
        Private counter As Integer = 0
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            MyTimer.Interval = 1000 '1 second
            MyTimer.Start()
        End Sub
    
        Private Sub MyTimer_Tick(sender As Object, e As EventArgs) Handles MyTimer.Tick
            counter += 1
            Me.Text = counter.ToString
            If counter > 10 Then MyTimer.Stop()
        End Sub
    End Class
    

    If you run this application, the form's load event sets the timer's interval to 1000 ms (1 second) and starts the timer. Every second, the timer's Tick event is fired and the Tick event handler increments a counter and displays the value in the form's header. When the counter exceeds 10, the timer is stopped.

    Saturday, October 4, 2014 1:01 PM
  • Hello,

    What follows demonstration is a bit more advance but thought it prudent to show.

    The following example uses a timer in a class project called from a windows form project. Please note "as is" this will only work if you are targeting Framework 4.5 because Task-based Asynchronous Pattern (TAP) methods used in tangent with the timer.

    Form code

    First button has no cancel while the second button provides a method to cancel

    Public Class Form1
        Private Sub cmdExecute_Click(sender As Object, e As EventArgs) Handles cmdExecute1.Click
            Dim r As New RunnerOne(CInt(nudMilliSeconds.Value), Label1)
            r.Execute()
        End Sub
        ''' <summary>
        ''' Declared at form level so we can perform a cancellation
        ''' </summary>
        ''' <remarks></remarks>
        Private TheRunner As New RunnerTwo
        Private Async Sub cmdExecute2_Click(sender As Object, e As EventArgs) Handles cmdExecute2.Click
            cmdExecute2.Enabled = False
            Await TheRunner.Execute(20, CInt(nudMilliSeconds.Value), CInt(nudMilliSeconds.Value))
            cmdExecute2.Enabled = True
        End Sub
        Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdCancel.Click
            TheRunner.TimerStop()
            cmdExecute2.Enabled = True
        End Sub
    End Class
    


    Class project code

    Public Class StateInformation
        Public Iterator As Integer
        Public Timer As System.Threading.Timer
        Public TimerCanceled As Boolean
    End Class
     

    Meat and potatoes which implements the timer

    ''' <summary>
    ''' There are two different timers demo'd here.
    ''' No import statements where used as w/i import
    ''' statements things are clearer.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class RunnerOne
        Public Property Timer As System.Timers.Timer
        Public Property MilliSecondsInterval As Integer
    
        Private mCounter As Integer = 0
        Private Label As System.Windows.Forms.Label
    
        Public Sub New(ByVal MilliSecondsInterval As Integer)
            Me.Timer = New System.Timers.Timer
            Me.MilliSecondsInterval = MilliSecondsInterval
            AddHandler Me.Timer.Elapsed, AddressOf tt_Elapsed
        End Sub
        Public Sub New(ByVal Interval As Integer, ByVal Label As System.Windows.Forms.Label)
            Me.Timer = New System.Timers.Timer
            Me.MilliSecondsInterval = Interval
            Me.Label = Label
            AddHandler Me.Timer.Elapsed, AddressOf tt_Elapsed
        End Sub
        Public Async Function Execute() As Task
            Me.Timer.Start()
            Await Task.Delay(Me.MilliSecondsInterval)
            Me.Timer.Stop()
    
            Me.Timer.Start()
            Await Task.Delay(Me.MilliSecondsInterval)
            Me.Timer.Stop()
    
            Me.Timer.Dispose() ' permanently stop timer
    
            Me.Label.BeginInvoke(New Action(Sub() Me.Label.Text = "Total iterations: " & mCounter.ToString))
        End Function
        Private Sub tt_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs)
            mCounter += 1
            Me.Label.BeginInvoke(New Action(Sub() Me.Label.Text = mCounter.ToString))
        End Sub
    End Class
    Public Class RunnerTwo
        Public Property Timer As System.Threading.Timer
        Private StateInfo As New StateInformation
    
        Public Sub New()
        End Sub
        Public Async Function TimerStop() As Task
            Await Task.Delay(500)
            If Not StateInfo.TimerCanceled Then
                Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
                StateInfo.TimerCanceled = True
                Console.WriteLine("Stopped, did not complete as per request")
            Else
                Console.WriteLine("To late, already done")
            End If
        End Function
        Public Async Function Execute(ByVal Iterations As Integer, ByVal MilliSeconds As Integer, ByVal Delay As Integer) As Task
            StateInfo = New StateInformation
            StateInfo.TimerCanceled = False
            StateInfo.Iterator = 1
    
            Dim TimerDelegate As New System.Threading.TimerCallback(AddressOf TimerTask)
            Me.Timer = New System.Threading.Timer(TimerDelegate, StateInfo, MilliSeconds, MilliSeconds)
    
            StateInfo.Timer = Timer
    
            While StateInfo.Iterator < Iterations
                Console.WriteLine("Iteration {0} of {1}", StateInfo.Iterator, Iterations)
                Await Task.Delay(Delay)
                If StateInfo.TimerCanceled Then
                    Exit While
                End If
            End While
    
            ' Request Dispose of the timer object.
            StateInfo.TimerCanceled = True
    
        End Function
        Private Sub TimerTask(ByVal sender As Object)
            Dim State As StateInformation = CType(StateInfo, StateInformation)
    
            System.Threading.Interlocked.Increment(State.Iterator)
            Console.WriteLine("Launched new thread  " & Now.ToString)
    
            If State.TimerCanceled Then
                State.Timer.Dispose()
                Console.WriteLine("Done  " & Now)
            End If
        End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Saturday, October 4, 2014 2:53 PM
  • how do I

    Susan 7 of 9

    A System.Windows.Forms timer is set to an interval for the code in the timer event to perform whatever it does.

    The timers interval can be set at any time via code.

    If the timer is already running when the interval is set to a new interval the new interval will not take effect until after the next time the timer event fires unless the timer is stopped and started which will cause it to use the new interval immediately.

    A timers time counter is not accurate as other system processes running in a multitasking OS may run something that causes the timers counter to be bumped for some interval until it starts counting again. Probably nano or microseconds at a time but it alters the accuracy of the timers counter.

    When the timers event handler fires at the end of its interval whatever code is in the timers event sub runs. However long it takes that code to finish the timers counter does not run again until that code is done.

    Here's a simple example of two timers being used to move labels in panels. It makes it look like scrolling text. I have to move them at 6 pixels at a time instead of 1 pixel at a time which is much smoother in order to create the animated .Gif so it would be small enough to post here.

    Option Strict On
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Panel1.BorderStyle = BorderStyle.Fixed3D
            Panel1.BackColor = Color.White
            Panel1.Size = New Size(232, 27)
            Panel1.Left = CInt((Me.ClientRectangle.Width / 2) - (Panel1.Width / 2))
    
            Panel2.BorderStyle = BorderStyle.Fixed3D
            Panel2.BackColor = Color.White
            Panel2.Size = New Size(232, 27)
            Panel2.Left = CInt((Me.ClientRectangle.Width / 2) - (Panel1.Width / 2))
    
            Label1.Font = New Font("Book Antiqua", 14)
            Label1.Text = "This text scrolls from right to left."
            Label1.Left = Panel1.Width
    
            Label2.Font = New Font("Book Antiqua", 14)
            Label2.Text = "This text scrolls from left to right."
            Label2.Left = Panel2.Width
    
            Timer1.Interval = 10
            Timer2.Interval = 10
    
            Timer1.Start()
            Timer2.Start()
    
        End Sub
    
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Label1.Left -= 6
            If Label1.Left + Label1.Width < 0 Then
                Label1.Left = Panel1.Width
            End If
        End Sub
    
        Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
            If Label2.Left > Panel2.Width Then
                Label2.Left = -Label2.Width
            End If
            Label2.Left = Label2.Left + 6
        End Sub
    
    End Class



    La vida loca




    Saturday, October 4, 2014 5:08 PM

All replies

  • Hi,

     There are several examples and tutorials on the net for using a Timer. Take a look at the link below.   8)

    Example of the timer control in VB.net

     

     Here is the msdn link to the Timer class that you can use to learn a little about the Methods, Properties, and Events of a Timer.

    Timer Class


    If you say it can`t be done then i`ll try it

    Saturday, October 4, 2014 12:58 PM
  • There are several types of timer and there are many things you might want to do with a timer. Here is a simple example.

    • Create a Windows forms project.
    • In the forms designer, drag a Timer onto the form from the Components section of the toolbox.
    • Change the timer's name property to MyTimer.
    • Double-click on the timer in the designer. You will be taken to the code window and a Click Event handler will be created.
    • Change the forms class to look like this.
    Option Strict On
    Option Explicit On
    
    Public Class Form1
    
        Private counter As Integer = 0
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            MyTimer.Interval = 1000 '1 second
            MyTimer.Start()
        End Sub
    
        Private Sub MyTimer_Tick(sender As Object, e As EventArgs) Handles MyTimer.Tick
            counter += 1
            Me.Text = counter.ToString
            If counter > 10 Then MyTimer.Stop()
        End Sub
    End Class
    

    If you run this application, the form's load event sets the timer's interval to 1000 ms (1 second) and starts the timer. Every second, the timer's Tick event is fired and the Tick event handler increments a counter and displays the value in the form's header. When the counter exceeds 10, the timer is stopped.

    Saturday, October 4, 2014 1:01 PM
  • how do I

    Additionally, you might find this article interesting. It compares the various types of timers available in dotNET.

    Still lost in code, just at a little higher level.

    :-)

    Saturday, October 4, 2014 2:20 PM
  • Hello,

    What follows demonstration is a bit more advance but thought it prudent to show.

    The following example uses a timer in a class project called from a windows form project. Please note "as is" this will only work if you are targeting Framework 4.5 because Task-based Asynchronous Pattern (TAP) methods used in tangent with the timer.

    Form code

    First button has no cancel while the second button provides a method to cancel

    Public Class Form1
        Private Sub cmdExecute_Click(sender As Object, e As EventArgs) Handles cmdExecute1.Click
            Dim r As New RunnerOne(CInt(nudMilliSeconds.Value), Label1)
            r.Execute()
        End Sub
        ''' <summary>
        ''' Declared at form level so we can perform a cancellation
        ''' </summary>
        ''' <remarks></remarks>
        Private TheRunner As New RunnerTwo
        Private Async Sub cmdExecute2_Click(sender As Object, e As EventArgs) Handles cmdExecute2.Click
            cmdExecute2.Enabled = False
            Await TheRunner.Execute(20, CInt(nudMilliSeconds.Value), CInt(nudMilliSeconds.Value))
            cmdExecute2.Enabled = True
        End Sub
        Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdCancel.Click
            TheRunner.TimerStop()
            cmdExecute2.Enabled = True
        End Sub
    End Class
    


    Class project code

    Public Class StateInformation
        Public Iterator As Integer
        Public Timer As System.Threading.Timer
        Public TimerCanceled As Boolean
    End Class
     

    Meat and potatoes which implements the timer

    ''' <summary>
    ''' There are two different timers demo'd here.
    ''' No import statements where used as w/i import
    ''' statements things are clearer.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class RunnerOne
        Public Property Timer As System.Timers.Timer
        Public Property MilliSecondsInterval As Integer
    
        Private mCounter As Integer = 0
        Private Label As System.Windows.Forms.Label
    
        Public Sub New(ByVal MilliSecondsInterval As Integer)
            Me.Timer = New System.Timers.Timer
            Me.MilliSecondsInterval = MilliSecondsInterval
            AddHandler Me.Timer.Elapsed, AddressOf tt_Elapsed
        End Sub
        Public Sub New(ByVal Interval As Integer, ByVal Label As System.Windows.Forms.Label)
            Me.Timer = New System.Timers.Timer
            Me.MilliSecondsInterval = Interval
            Me.Label = Label
            AddHandler Me.Timer.Elapsed, AddressOf tt_Elapsed
        End Sub
        Public Async Function Execute() As Task
            Me.Timer.Start()
            Await Task.Delay(Me.MilliSecondsInterval)
            Me.Timer.Stop()
    
            Me.Timer.Start()
            Await Task.Delay(Me.MilliSecondsInterval)
            Me.Timer.Stop()
    
            Me.Timer.Dispose() ' permanently stop timer
    
            Me.Label.BeginInvoke(New Action(Sub() Me.Label.Text = "Total iterations: " & mCounter.ToString))
        End Function
        Private Sub tt_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs)
            mCounter += 1
            Me.Label.BeginInvoke(New Action(Sub() Me.Label.Text = mCounter.ToString))
        End Sub
    End Class
    Public Class RunnerTwo
        Public Property Timer As System.Threading.Timer
        Private StateInfo As New StateInformation
    
        Public Sub New()
        End Sub
        Public Async Function TimerStop() As Task
            Await Task.Delay(500)
            If Not StateInfo.TimerCanceled Then
                Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
                StateInfo.TimerCanceled = True
                Console.WriteLine("Stopped, did not complete as per request")
            Else
                Console.WriteLine("To late, already done")
            End If
        End Function
        Public Async Function Execute(ByVal Iterations As Integer, ByVal MilliSeconds As Integer, ByVal Delay As Integer) As Task
            StateInfo = New StateInformation
            StateInfo.TimerCanceled = False
            StateInfo.Iterator = 1
    
            Dim TimerDelegate As New System.Threading.TimerCallback(AddressOf TimerTask)
            Me.Timer = New System.Threading.Timer(TimerDelegate, StateInfo, MilliSeconds, MilliSeconds)
    
            StateInfo.Timer = Timer
    
            While StateInfo.Iterator < Iterations
                Console.WriteLine("Iteration {0} of {1}", StateInfo.Iterator, Iterations)
                Await Task.Delay(Delay)
                If StateInfo.TimerCanceled Then
                    Exit While
                End If
            End While
    
            ' Request Dispose of the timer object.
            StateInfo.TimerCanceled = True
    
        End Function
        Private Sub TimerTask(ByVal sender As Object)
            Dim State As StateInformation = CType(StateInfo, StateInformation)
    
            System.Threading.Interlocked.Increment(State.Iterator)
            Console.WriteLine("Launched new thread  " & Now.ToString)
    
            If State.TimerCanceled Then
                State.Timer.Dispose()
                Console.WriteLine("Done  " & Now)
            End If
        End Sub
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Saturday, October 4, 2014 2:53 PM
  • how do I

    Susan 7 of 9

    A System.Windows.Forms timer is set to an interval for the code in the timer event to perform whatever it does.

    The timers interval can be set at any time via code.

    If the timer is already running when the interval is set to a new interval the new interval will not take effect until after the next time the timer event fires unless the timer is stopped and started which will cause it to use the new interval immediately.

    A timers time counter is not accurate as other system processes running in a multitasking OS may run something that causes the timers counter to be bumped for some interval until it starts counting again. Probably nano or microseconds at a time but it alters the accuracy of the timers counter.

    When the timers event handler fires at the end of its interval whatever code is in the timers event sub runs. However long it takes that code to finish the timers counter does not run again until that code is done.

    Here's a simple example of two timers being used to move labels in panels. It makes it look like scrolling text. I have to move them at 6 pixels at a time instead of 1 pixel at a time which is much smoother in order to create the animated .Gif so it would be small enough to post here.

    Option Strict On
    
    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Panel1.BorderStyle = BorderStyle.Fixed3D
            Panel1.BackColor = Color.White
            Panel1.Size = New Size(232, 27)
            Panel1.Left = CInt((Me.ClientRectangle.Width / 2) - (Panel1.Width / 2))
    
            Panel2.BorderStyle = BorderStyle.Fixed3D
            Panel2.BackColor = Color.White
            Panel2.Size = New Size(232, 27)
            Panel2.Left = CInt((Me.ClientRectangle.Width / 2) - (Panel1.Width / 2))
    
            Label1.Font = New Font("Book Antiqua", 14)
            Label1.Text = "This text scrolls from right to left."
            Label1.Left = Panel1.Width
    
            Label2.Font = New Font("Book Antiqua", 14)
            Label2.Text = "This text scrolls from left to right."
            Label2.Left = Panel2.Width
    
            Timer1.Interval = 10
            Timer2.Interval = 10
    
            Timer1.Start()
            Timer2.Start()
    
        End Sub
    
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Label1.Left -= 6
            If Label1.Left + Label1.Width < 0 Then
                Label1.Left = Panel1.Width
            End If
        End Sub
    
        Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
            If Label2.Left > Panel2.Width Then
                Label2.Left = -Label2.Width
            End If
            Label2.Left = Label2.Left + 6
        End Sub
    
    End Class



    La vida loca




    Saturday, October 4, 2014 5:08 PM