Using Timers


In the world of electronics, a timer is a device you can use to activate another device after a certain period of time. For example, you can use a timer to switch on an electronic kettle for 15 minutes at 6:00 A.M. (so by the time you get out of the bed, you have boiling water for coffee). Or, you can install a timer in a car to trigger the alarm 20 seconds after the engine is started. (This gives the driver enough time to switch off the alarm.)

In .NET programming, you have several timer controls you can use for many different purposes. The classic example of the use of a timer is for displaying a splash screen. When the main application loads and initializes, the user is "entertained" by the splash screen that appears for five seconds and closes in time when the main application is ready. Or, as another example, in a video game, the bad guy will start chasing the hero two seconds after the hero's first move.

You can also use a timer to trigger recurring events. For instance, you can create an application that uses a timer to check every few seconds if a certain server is up and running. If it's not, the application can send a notification email to the administrator.

The .NET Framework class library provides several Timer classes. One is the member of the System.Windows.Forms namespace and is known as the Windows- based timer. The other one belongs to the System.Timers namespace and is called the server-based timer.

Note

There is another Timer class in the System.Threading namespace; however, it is not discussed in this chapter.

The System.Windows.Forms.Timer class is optimized for Windows applications and can only be used in a Windows application. The server-based timer is for a server environment. To use any of the timer classes, you wire an event handler that is to be executed when the timer goes off. You also set the Interval property to indicate the number of milliseconds the timer will go off after it is started. Both classes are explained in the next two subsections with examples.

Using the Windows-Based Timer

The Windows-based timer works in a single-threaded environment and uses the User Interface (UI) thread to perform processing. These timers require that the user code have a UI message pump available and always operate from the same thread. Windows-based timers have accuracy limited to 55 milliseconds.

The System.Windows.Forms.Timer class has one event: Tick. When the timer is on, this event is raised repeatedly every specified amount of time. The value of the class's Interval property indicates the specified amount of time. For instance, if the value of the Interval property is 3000, the Tick event is raised once every 3,000 milliseconds.

By default, the Timer is off when it is instantiated. As such, the Tick event will not be raised regardless of the value of the Interval property. To switch on the timer, you can either set the Timer class's Enabled property to True or call its Start method.

To switch it off, you set the Enabled property to False or invoke the Timer class's Stop method.

As an example, Listing 3-2 is a form that displays a splash screen for five seconds. The splash screen is displayed two seconds after the form is instantiated. To achieve this, it uses the System.Windows.Forms.Timer class.

Listing 3-2: A Splash Screen Using the Windows-Based Timer

start example
 Imports System Imports System.Windows.Forms Public Class Form1 : Inherits Form   Private theTimer As New Timer()   Private splash As New Form()   Private splashShown As Boolean = False   Public Sub New()     AddHandler theTimer.Tick, AddressOf theTimer_Tick     theTimer.Interval = 2000     theTimer.Start()   End Sub   Private Sub theTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)     If Not splashShown Then       splash.Text = "Splash screen"       splash.Show()       ' show the splash screen for 5 seconds       theTimer.Interval = 5000       splashShown = True     Else       'close the splash screen       splash.Close()       theTimer.Enabled = False     End If   End Sub   <STAThread()> Shared Sub Main()     Application.Run(New Form1())   End Sub End Class 
end example

To compile this application, from the directory where the listing-03.02.vb file resides, type the following:

 vbc /t:winexe /r:System.dll,System.Windows.Forms.dll,  System.Drawing.dll listing-03.02.vb 

When run, you will first see a Windows form. After two seconds, another form appears. The second form will disappear in five seconds.

To understand how the application works, first note the declaration part of the Form class:

 Private theTimer As New Timer() Private splash As New Form() Private splashShown As Boolean = False 

The theTimer variable is an object reference to a Windows-based timer control. splash is a form that is to be displayed as a splash screen. splashShown is a Boolean that will be used to switch off the timer.

When the Form1 class's constructor is called, it wires the Timer class's Tick event with an event handler called theTimer_Tick:

 AddHandler theTimer.Tick, AddressOf theTimer_Tick 

The timer's Interval property is then set to 2000, indicating that the timer will go off once in every two seconds, triggering the timer's Tick event. As a result, the theTimer_Tick event handler will execute every two seconds:

 theTimer.Interval = 2000 

To start the timer, you call the Timer class's Start method:

 theTimer.Start() 

You see that the code in the Form1 class's constructor will make the Timer object's Tick event trigger repeatedly. However, you only want the timer to be executed twice: once to display the splash screen and once to close it. You achieve this using the splashShown Boolean in the theTimer_Tick event handler.

The initial value of splashShown is False. Therefore, when the Tick event is raised for the first time, the theTimer_Tick event handler executes the code in the If block. It first sets the Text property of the splash screen form and displays the splash screen by calling the Show method:

 splash.Text = "Splash screen" splash.Show() 

You want the splash screen to appear for five seconds, so you set the Interval property of the Timer object to 5000 and set splashShown to True:

 ' show the splash screen for 5 seconds theTimer.Interval = 5000 splashShown = True 

Five seconds later, the timer's Tick event is raised again. This time the value of splashShown is True, so the code in the Else block in the theTimer_Tick event handler is executed.

It first calls the splash screen's Close method to close the splash screen:

 'close the splash screen splash.Close() 

Then, it sets the Timer class's Enabled property to False, in effect deactivating the timer:

 theTimer.Enabled = False 

Because its Enabled property is set to False, the timer will not go off again. Therefore, during the life of the application, the timer only goes off twice.

Using the Server-Based Timer

The server-based timer uses worker threads in a multithreaded environment and are more accurate than Windows-based timers because of their architecture. Best of all, server-based timers can move among threads to handle the raised events. You can also use server-based timers in a Windows application, as in this chapter's Doggie project.

The System.Timers.Timer class has one event, Elapsed, which is raised when a specified amount of time elapses after the timer is started. The Timer class's Interval property indicates the amount of time. For instance, if the value of the Interval property is 4000, the Elapsed event triggers 4,000 milliseconds after the timer is started.

The value of the AutoReset property determines whether the Elapsed event will trigger again. If its value is True, the Elapsed event will be raised again. If the value of the AutoReset property is False, the Elapsed event will not be triggered again. By default, the value of the AutoReset property is True.

Like the Windows-based timer, you can switch on the server-based timer by calling its Start method or setting its Enabled property to True. You switch it off by calling its Stop method or setting its Enabled property to False.

Another difference between the System.Timers.Timer class and the System.Windows.Forms.Timer class is the type of event argument passed to the event handler that handles the method when the Tick event or Elapsed event is raised. With the Windows-based timer, it is a System.EventArgs object. With the serverbased timer, it is a System.Timers.ElapsedEventArgs object.

The System.Timers.ElapsedEventArgs class has one property: SignalTime. This property returns a System.DateTime object indicating the time the Elapsed event was raised. You need this property because the System.Timers.Timer class is multithreaded, so the call to its event handler may run on one thread while a call to the Stop method runs on another thread. This means that the Elapsed event might trigger after the Stop method is called. To prevent this from happening, you can use the SignalTime property to compare the time the event is raised with the time the Stop method is called. If the event is raised after the Stop method is called, you have the disposal not to process the event.

Listing 3-3 offers a similar example to display a splash screen. However, this example uses a server-based timer.

Listing 3-3: Displaying a Splash Screen Using a Server-Based Timer

start example
 Imports System Imports System.Windows.Forms Public Class Form1 : Inherits Form   Private theTimer As New System.Timers.Timer()   Private splash As New Form()   Private splashShown As Boolean = False   Public Sub New()     AddHandler theTimer.Elapsed, AddressOf theTimer_Elapsed     theTimer.Interval = 2000     theTimer.Start()   End Sub   Private Sub theTimer_Elapsed(ByVal sender As Object, _     ByVal e As System.Timers.ElapsedEventArgs)     If Not splashShown Then       splash.Text = "Splash screen"       splash.Show()       ' show the splash screen for 5 seconds       theTimer.Interval = 5000       splashShown = True     Else       'close the splash screen       splash.Close()       theTimer.AutoReset = False     End If   End Sub   <STAThread()> Shared Sub Main()     Application.Run(New Form1())   End Sub End Class 
end example

To compile this application, from the directory where the listing-03.03.vb file resides, type the following:

 vbc /t:winexe /r:System.dll,System.Windows.Forms.dll,  System.Drawing.dll listing-03.03.vb 

In the Form1 class's constructor, you wire the Elapsed event of the Timer class with an event handler theTimer_Elapsed. Note that the event handler receives a System.Timers.ElapsedEventArgs.

Also, when the Elapsed event is raised for the second time, you set the AutoReset property to False, instead of resetting the Enabled property.




Real World. NET Applications
Real-World .NET Applications
ISBN: 1590590821
EAN: 2147483647
Year: 2005
Pages: 82

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net