The Timer class (server-based timer) lets you specify a recurring interval at
which the elapsed event is raised. This way we can do regular processing inside
the event code block when the timer event occurs. Timers are used to generate
recurring events in an application. Some members of the Timer class are
described in Table 21.10.
Table 21.10: Timer Class Members

We use the Timer class to work with worker threads in a multithreaded
environment; it is based on server-based timers rather than Windows timers.
Server-based timers are more reliable than Windows timers. With server-based
timers, we can move among threads to handle the raised elapsed event. Windows
timers, on the other hand, were not really intended for switching between
threads. The Windows timer is optimized for use in Windows Forms applications
and is assumed to be thread-safe. The server-based timer is an updated Windows
timer that has been optimized to run in a multithreaded server environment. The
Windows timer lives in the System.Windows.Forms namespace, and the server-based
timer resides in the System.Timers namespace. Intervals are specified in
milliseconds for timers, to trigger events after that time has gone. When the
AutoReset field of the Timer class is set to false, the elapsed event is
triggered only once by the timer after the first interval has elapsed. If you
want to raise the elapsed event each time the time interval occurs in
perpetuity, set AutoReset to true. Since both timer usages are almost identical,
we choose to demonstrate the server-based timer because of its multithreaded
nature. The sample example given below shows how to use a Timer object that is
triggered on 1,000-millisecond intervals.
Example of Using Timers
Imports System.Timers
Imports
System.Threading
Public Class Test
Public Shared Sub
Main()
Dim myTimer As New
System.Timers.Timer()
AddHandler myTimer.Elapsed, New ElapsedEventHandler(AddressOf
OnTimer)
myTimer.Interval = 1000
myTimer.Enabled = True
myTimer.AutoReset = False
While Console.Read()
Thread.Sleep(1000)
End While
End Sub
Public Shared Sub
OnTimer(ByVal
source As [Object],
ByVal
e As ElapsedEventArgs)
Console.WriteLine("DateTime:
" & DateTime.Now)
Dim theTimer As
System.Timers.Timer
= DirectCast(source,
System.Timers.Timer)
theTimer.Interval += 1000
theTimer.Enabled = True
End Sub
End Class
Timer Output from One-Second

Notice the time difference between each time trigger. This shows that the
server-based timers are not pulsing as we expected, because although we enabled
our timer to trigger every one second, the event handler was delayed in order to
handle other activity of the CPU. Server-based timers are dependent on the
operating system's multithreading character on which our code runs, and the
program must obey the CPU priority rules when using these timers.
Conclusion
Hope this article would have helped you in understanding Timers in VB.NET