using System; using System.Timers; public class TimerExample { private static Timer _timer; public static void Main(string[] args) { _timer = new Timer(1000); // Defines timer interval of 1000 milliseconds _timer.Elapsed += OnTimedEvent; // Assign OnTimedEvent handler to Elapsed event _timer.Enabled = true; // Enable the timer Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); } private static void OnTimedEvent(Object source, ElapsedEventArgs e) { Console.WriteLine($"The Elapsed event was raised at {e.SignalTime}"); } }
using System; using System.Timers; public class TimerExample { private static Timer _timer; private static int _count = 0; public static void Main(string[] args) { _timer = new Timer(1000); // Defines timer interval of 1000 milliseconds _timer.Elapsed += OnTimedEvent; // Assign OnTimedEvent handler to Elapsed event _timer.Enabled = true; // Enable the timer Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); } private static void OnTimedEvent(Object source, ElapsedEventArgs e) { _count++; Console.WriteLine($"Timer event {_count} at {e.SignalTime}"); if (_count == 10) { _timer.Enabled = false; // Stop the timer after 10 events Console.WriteLine("Timer stopped."); } } }This example creates a timer that executes the OnTimedEvent handler every second and prints the count of how many events have been raised. It stops the timer after 10 events have been raised.