Using the Timer Class

by Shabbir on May 22, 2008

in C#

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

  1. using System.Timers;

Then in the Main() function put this code

  1. Timer tm = new Timer();
  2. tm.Interval = 1000;
  3. tm.Elapsed += new ElapsedEventHandler(tm_Elapsed);
  4. tm.Enabled = true;
  5.  
  6. Console.WriteLine("To exit hit the \"Enter\" key.");
  7. 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

  1. static void tm_Elapsed(object sender, ElapsedEventArgs e)
  2. {
  3. Console.WriteLine(DateTime.Now);
  4. }

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.

Sharing is Caring...

Leave a Comment

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.