C# Working with Timer Object

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.

About these ads


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.