How to Use Timer in C#: Simple Guide with Examples
In C#, you can use the
System.Timers.Timer class to run code repeatedly at set intervals. Create a Timer, set its Interval, attach an event handler to Elapsed, and start it with Start().Syntax
The basic syntax to use a Timer in C# involves creating an instance of System.Timers.Timer, setting the interval in milliseconds, attaching an event handler to the Elapsed event, and starting the timer.
- Timer timer = new Timer(interval); - creates a timer with the specified interval.
- timer.Elapsed += EventHandler; - sets the method to call when the timer ticks.
- timer.AutoReset = true; - makes the timer repeat automatically.
- timer.Start(); - starts the timer.
csharp
using System.Timers; Timer timer = new Timer(1000); // 1000 ms = 1 second timer.Elapsed += OnTimedEvent; timer.AutoReset = true; timer.Start(); void OnTimedEvent(object sender, ElapsedEventArgs e) { // Code to run every interval }
Example
This example shows how to create a timer that prints a message every second and stops after 5 seconds.
csharp
using System; using System.Timers; class Program { private static Timer timer; private static int count = 0; static void Main() { timer = new Timer(1000); // 1 second interval timer.Elapsed += OnTimedEvent; timer.AutoReset = true; timer.Enabled = true; Console.WriteLine("Timer started. Press Enter to exit early."); Console.ReadLine(); } private static void OnTimedEvent(object sender, ElapsedEventArgs e) { count++; Console.WriteLine($"Timer tick {count} at {e.SignalTime:HH:mm:ss}"); if (count >= 5) { timer.Stop(); timer.Dispose(); Console.WriteLine("Timer stopped after 5 ticks."); } } }
Output
Timer started. Press Enter to exit early.
Timer tick 1 at 12:00:01
Timer tick 2 at 12:00:02
Timer tick 3 at 12:00:03
Timer tick 4 at 12:00:04
Timer tick 5 at 12:00:05
Timer stopped after 5 ticks.
Common Pitfalls
- Not keeping the program alive: The timer runs on a separate thread, so if the main program ends, the timer stops immediately.
- Forgetting to set
AutoReset: IfAutoResetis false, the timer runs only once. - Thread safety: The
Elapsedevent runs on a thread pool thread, so avoid updating UI elements directly. - Not disposing the timer: Always call
Dispose()to free resources when done.
csharp
/* Wrong: Timer stops immediately because program exits */ using System.Timers; class Program { static void Main() { Timer timer = new Timer(1000); timer.Elapsed += (s, e) => Console.WriteLine("Tick"); timer.Start(); // Program ends here, timer stops } } /* Right: Keep program alive to see timer ticks */ using System; using System.Timers; class Program { static void Main() { Timer timer = new Timer(1000); timer.Elapsed += (s, e) => Console.WriteLine("Tick"); timer.Start(); Console.ReadLine(); // Wait for user input } }
Quick Reference
- Timer(interval): Create timer with interval in milliseconds.
- Elapsed: Event triggered on each tick.
- AutoReset: True to repeat, false to run once.
- Start(): Begin timer.
- Stop(): Stop timer.
- Dispose(): Release resources.
Key Takeaways
Use System.Timers.Timer to run code repeatedly at set intervals.
Attach your code to the Elapsed event and start the timer with Start().
Keep your program running to allow the timer to tick.
Set AutoReset to true for repeated ticks, false for a single tick.
Always dispose the timer when finished to free resources.