CountDown timer Class using VB.NET

Timers plays an very important role in both server-based components and client applications. They provides a way for the user to call a subroutine every several seconds.
  • 5315

CountDown timer Class in .NET

Timers plays an very important role in both server-based components and client applications. They provides a way for the user to call a subroutine every several seconds.


First, you have to construct the Timer instance and then add handlers to it to provide regular processing. The ElapsedEventHandler specifies a subroutine to perform the maintenance or updating code.


The following code example sets up an timer, which specifies its interval as 1000 milliseconds (1 seconds) and then we call the AddHandler operator to assign the Handler subroutine. At last, we set the Enabled property to True to start the Timer. Lets see the code snippets for that.

Code

Imports System
Imports System.Timers
Public Class Timer1
    Private Shared aTimer As System.Timers.Timer
    Public Shared Sub Main()
        'Dim aTimer As System.Timers.Timer
      
        ' Create a timer with a ten second interval.
        aTimer = New System.Timers.Timer(10000)
       
        ' Hook up the Elapsed event for the timer.
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

        ' Set the Interval to 1 seconds (1000 milliseconds).
        aTimer.Interval = 1000
        aTimer.Enabled = True 
        Console.WriteLine("Press the Enter key to exit the program.")
        Console.ReadLine()

        ' Use KeepAlive to prevent garbage collection from occuring
        ' before this method ends,
        ' If the timer is declared in a long-running method.
        'GC.KeepAlive(aTimer)
    End Sub 

    ' Specify what you want to happen when the Elapsed event is raised.
    Private Shared Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub
End Class

Output

timer.gif

Summary

Hope this article will help you to understand the System.Timers namespace in which provides the timer component to raise an event on a specified interval defined by user.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.