Home About

November 21st, 2008

Using Timers in C# - 0

Sometimes its handy to set an alarm clock — to tell you when to get that next cup of coffee for example. Your C# programs also might want to check that everything is going smoothly. Timers are handy if you want to check for example whether that download has stalled, a message needs to be send or a file needs to be updated.

Creating a timer in C# is very simple. You need to create an instance of System.Timers.Timer (which in this case we need to spell out, as it has a name conflict with System.Threading.Timer) and assign a callback function. The callback function is called each time the timer event is fired, there is no need to reset the timer as the system will continue to call it automatically.

The following example sets a timer that prints the time of its firing roughly every second. Note that the timing of each event is not exact. After the set period has expired C# queues a ThreadPool task which will then try to find an available thread to actually execute the callback.

We need to assign the callback to the “Elapsed” event property. If we also would like to fire an event when the Timer is disposed off, we can attach an event to disposed — but this is optional.

using System;
using System.Timers;
using System.Threading;

public class TimerExample
{
    // Our timer
    private static System.Timers.Timer TheTimer;

    public static void Main()
    {
        TheTimer = new System.Timers.Timer();

        TheTimer.Elapsed += new ElapsedEventHandler(OurTimerCallback);
        TheTimer.Disposed += new EventHandler(OurTimerDisposed); 
        TheTimer.Interval = 1000;
        TheTimer.Enabled = true;

        Console.WriteLine("Press 'x' to quit");
        CheckForExitKey();
			
		// Allow the timer to clean up
		TheTimer.Dispose();
        
        Console.WriteLine("Main exits.");
    }

    public static void OurTimerCallback(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Received a callback, the time is {0}", e.SignalTime);
    }

    public static void OurTimerDisposed(object source, EventArgs e)
    {
        Console.WriteLine("Called when the timer is disposed off");
    }

    public static void CheckForExitKey()
    {
        ConsoleKeyInfo cki = new ConsoleKeyInfo();
        while (true)
        {
           while (Console.KeyAvailable == false)
            Thread.Sleep(250); // We poll -- since no event exists, wait for 250ms
           cki = Console.ReadKey(true);
           if (cki.Key == ConsoleKey.X) break;
        }
    }

}
Be Sociable, Share!

Tags: , ,

Comments are closed.


Most popular
Recent Comments
  • ARS: great plugin! I love it! but, it will be so nice if you can add attribute ‘title’ as one of...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to somewhere there...
  • berties: any english speaking playing on a taiwanese server?
  • web application development: has C# search volume really so constant over the years? really surprising.