Robert Robert - 1 year ago 67
C# Question

What is the best way to implement a "timer"?

Possible Duplicate:

How do you add a timer to a C# console application

What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 seconds, not every 10 - 20 seconds. On the other hand, I don't need nanosecond accuracy. In this example, it would be acceptable for the method to fire every 14.51 - 15.49 seconds.

Answer Source

Use the Timer class.

public static void Main()
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);

    Console.WriteLine("Press \'q\' to quit the sample.");

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
     Console.WriteLine("Hello World!");

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify, in the example above it is OnTimedEvent