Home >Backend Development >C#.Net Tutorial >Timer in C#
The namespace used to set timers is System.Timers. The Timer class generates an event after a set interval and optionally generates recurring events.
First, create a timer object with a 5-second interval −
timer = new System.Timers.Timer(5000);
Set the timer elapsed event. This event occurs when the interval elapses −
timer.Elapsed += OnTimedEvent;
Start timing now. The Chinese translation of
timer.Enabled = true;
using System; using System.Timers; public class Demo { private static Timer timer; public static void Main() { timer = new System.Timers.Timer(); timer.Interval = 5000; timer.Elapsed += OnTimedEvent; timer.AutoReset = true; timer.Enabled = true; Console.WriteLine("Press the Enter key to exit anytime... "); Console.ReadLine(); } private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) { Console.WriteLine("Raised: {0}", e.SignalTime); } }
The above is the detailed content of Timer in C#. For more information, please follow other related articles on the PHP Chinese website!