By Shabbir Bhimani
Expert Author
Article Date: 2008-11-06
The timer class is often used in many applications. It's very simple for using, like all the classes implemented in .Net Framework.
So create a C# Console project, we will try this class in a console application.
Include this namespace, so we can use the Timer class
usingSystem.Timers;
Then in the Main() function put this code
Timer tm = new Timer();tm.Interval = 1000;tm.Elapsed += new ElapsedEventHandler(tm_Elapsed);tm.Enabled = true; Console.WriteLine("To exit hit the "Enter" key.");Console.ReadLine();
In the above code we are creating an object from the Timer class, set his interval so 1000 miliseconds, create an event which will be invoked every 1000 miliseconds and enable the timer.
Then we write some text to the console, just for information for the user how to exit from the application. And the last line stops the program to end, and waits for user input.
Below the main function create this event
staticvoid tm_Elapsed(object sender, ElapsedEventArgs e){Console.WriteLine(DateTime.Now);}
In the end you can exclude the unused usings, showed in this post.
Now start the application, it will write on the console the actual time every second. Press Enter to exit.
You can put diferrent code in the tm_Elapsed function, so that code will execute every second or the interval you will set.
Download the project from here.
Comments