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

using System.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

static void 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.

Share:
  • Digg
  • Facebook
  • StumbleUpon
  • Technorati
  • Twitter
Other Related Posts:
  1. Read From File Using StreamReader Class
  2. Usage Of RegistryKey Class
  3. Write To File in C#
  4. Write To File In C++
  5. Creating a Windows Forms Application in C#

Want More Tips on How to Make Money Online?
Enter your Name and Email below to subscribe and start 1 month free course now.

Name:
Email:
You would require to confirm your email address before we send you any updates. We respect your privacy as much as you do.
Powered by Aweber
blog comments powered by Disqus

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.