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
 


About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 13, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT APIs can be a great source of competitive advantage. The practice of exposing backend services as APIs has become pervasive, however their use varies widely across companies and industries. Some companies leverage APIs to create internal, operational and development efficiencies, while others use them to drive ancillary revenue channels. Many companies successfully support both public and private programs from the same API by varying levels …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds