C# Working with Timer Object
Posted: 13/01/2012 Filed under: Programming | Tags: C# Leave a comment »A timer object can be really helpful when there is a need of some form of scheduling. For example, writing entries into a log file hourly. MSDN defines the Timer class as an object that generates recurring events in an application.
The code snippet below shows a simple example using Timer to write out a line every 5 seconds (console application).
1: using System;
2: using System.Timers;
3:
4: static void Main(string[] args)
5: {
6: BeginSchedule();
7: Console.ReadKey();
8: }
9:
10: private static void BeginSchedule()
11: {
12: var timer = new Timer
13: {
14: // Gap between each event execution
15: // set to 5 seconds in miliseconds.
16: // Then timer is started.
17: Interval = 5000,
18: Enabled = true
19: };
20:
21: // Event that is called after each timer interval.
22: timer.Elapsed += new ElapsedEventHandler(TimerElapsedEvent);
23: }
24:
25: static void TimerElapsedEvent(object sender, ElapsedEventArgs e)
26: {
27: Console.WriteLine("5 seconds later.");
28: }
Code well.