- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Timer in C#
The namespace used to set a timer is System. Timers. The Timer class generates an event after a set interval, with an option to generate recurring events.
Firstly, create a timer object for 5 seconds interval −
timer = new System.Timers.Timer(5000);
Set elapsed event for the timer. This occurs when the interval elapses −
timer.Elapsed += OnTimedEvent;
Now start the timer.
timer.Enabled = true;
Example
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); } }
Advertisements