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;
        }
    }

}
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google
  • Reddit

Tags: , ,

Leave a Reply


Recent Comments
  • Ales: Hi, Thanks for the code… I must say I did not experience any errors decrypting any of my messages. I even...
  • JC: Thanks very useful and well explained
  • Thomas: This is a public static class written in the C# language that does not save state. You can call into the...
  • Simon: Thank you very much for this post! It helped me essentially to overcome obstacels to work with mono!
  • Graham: This is a good research for keyboard shortcuts! Some shortcuts are also compatible for Windows OS. I have...