Working with a Timer in C#: The Basics

The following listing presents a neat little program that is not well designed. It is simple, and there is nothing complex presented in it. It simply prints the time to the console. Forever.

Listing 1. timer.cs – Displaying the time.

 1:  //  Timer01.cs – Displaying Date and Time
2: // Not a great way to do the time.
3: // Press Ctrl+C to end program.
4: //——————————————
5: using System;
6:
7: class myApp
8: {
9: public static void Main()
10: {
11: while (true)
12: {
13: Console.Write(“\r{0}”, DateTime.Now);
14: }
15: }
16: }

*** Output ***

5/26/2003 9:34:19 PM

*** Analysis ***

As you can see, this listing was executed at 9:34 on May the 26th. This listing presents a clock on the command line. This clock seems to update the time every second. Actually it us updating much more often than that; however, you only notice the changes every second when the value being displayed actually changes. This program runs until you break out of it using Ctrl+C.

In line 13, a call to DateTime is made. DateTime is a structure that is available from the System namespace within the base class libraries. This structure has a static method called Now that returns the current time. There are a large number of additional data members and methods within the DateTime structure. You can check out the .NET Framework class library documentation for information on these. There are also a few other aritcles here on CodeGuru.com

A better way to present a date on the screen is with a timer. A timer allows a process—in the form of a delegate—to be called at a specific time or after a specific period of time has passed. The framework includes a class for timers within the System.Timers namespace. This class is appropriately called Timer. Listing 2 is a rewrite of listing 1 using a Timer.

Listing 2. Timer02.cs – Using a timer with the DateTime.

 1:  //  Timer02.cs - Displaying Date and Time
2: // Using the Timer class.
3: // Press Ctrl+C to end program.
4: //------------------------------------------
5: using System;
6: using System.Timers;
7:
8: class myApp
9: {
10: public static void Main()
11: {
12: Timer myTimer = new Timer();
13: myTimer.Elapsed += new ElapsedEventHandler( DisplayTimeEvent );
14: myTimer.Interval = 1000;
15: myTimer.Start();
16:
17: while ( Console.Read() != 'q' )
18: {
19: ; // do nothing...
20: }
21: }
22:
23: public static void DisplayTimeEvent( object source, ElapsedEventArgs e )
24: {
25: Console.Write("\r{0}", DateTime.Now);
26: }
27: }

*** Output ***

5/26/2003 10:04:13 PM

*** Analysis ***

As you can see, this listing's output is just like that of the previous listing. This listing, however, operates much better. Instead of constantly updating the date and time being displayed, this listing only updates it every 1000 ticks. 1000 ticks is equal to one second.

Looking closer at this listing, you can see how a Timer works. In line 12 a new Timer object is created. In line 14 the interval that is to be used is set. In line 13 the method that is to be executed after the interval is associated to the timer. In this case, the DisplayTimeEvent will be executed. This method is defined in lines 23 to 26.

In line 15 the Start method is called this will start the interval. Another member for the Timer class is the AutoReset member. If you change the default value from true to false, then the Timer event will happen only once. If the AutoReset is left at its default value of true, or set to true, then the Timer will fire an event and thus execute the method every time the given interval passes.

Line 17 to 20 contain a loop that continues to operate until the reader enters the letter 'q' and presses enter. Once the user does this, the end of the routine is reached and the program ends; otherwise, the program continues to spin in this loop. Nothing is done in this loop in this program. You can do other processing in this loop if you desired. There is no need to call the DisplayTimeEvent in this loop because it will be automatically called at the appropriate interval.

This timer is used to display the time on the screen. Timer and timer events can be used for numerous other programs as well. You could create a timer that fires off a program at a given time. You could create a backup routine that copies important data at a given interval. You could create a routine to automatically log off a user or end a program after a given time period with no activity. There are numerous ways to use timers.


This article is brought to you by Sams Publishing
and Bradley L. Jones.

Sams Teach Yourself the C# Language in 21 Days
© Copyright Bradley L. Jones, All Rights Reserved

 



More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read