Timer in C#

The Timer control allows you to set a time interval to peridically execute an event at a specified interval. It is useful when you want to execute certain applications after a certain interval. Say you want to create a hourly backup of your data. You can make a routine that will take the backup and call that routine in the Timer's event and set the timer interval for an hour.

Using the timer control is very simple. To test the control, I'm going to create a Windows Application. I also add two button controls to the form and change their text to Start and Stop as you can see from the following Figure.



In this application, I'm going to create a text file mcb.txt in your C:\temp directory and start writing the time after 5 seconds. The Stop button stops the timer and the Start starts the timer again.

Note: If you do not have a temp folder on your C:\ Drive, you must change this path.

Now you can drag a timer control from the toolbox to the form from the Toolbox of Visual Studio. You can set the timer properties from the IDE as well as programmatically. To set the timer properties, right-click on the timer control and change the Interval property. As you can see from the Figure,

I used 5000 milliseconds (5 seconds).

1 sec = 1000 milliseconds.



Now click on the Events button and write the event for the timer click as you can see from the following figure:



Now I add a FileStream and a StreamWriter object in the beginning of the class. As you can see from the following code, the FileStream class creates a mcb.txt file and StreamWriter will be used to write to the file.

private static FileStream fs = new
FileStream(@"c:\temp\mcb.txt", FileMode.OpenOrCreate, FileAccess.Write);
private static StreamWriter m_streamWriter = new
StreamWriter(fs);

Now write the following code in the Form Load event:

private void Form1_Load(object sender, System.EventArgs e)
{
// Write to the file using StreamWriter class
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(" File Write Operation Starts : ");
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine(" ===================================== \n");
m_streamWriter.Flush();
}

As you can see from the above code, this code writes some lines to the file.

Now write code on the Start and Stop button click handlers. As you can see from the following code, the Start button click sets the timer's Enabled property to true. Setting the timer's Enabled property starts the timer to execute the timer event. I set the Enabled property to false on the Stop button click event handler, that stops executing the timer tick event.

private void button1_Click(object sender, System.EventArgs e)
{
timer1.Enabled =
true
;
}
private void button2_Click(object
sender, System.EventArgs e)
{
timer1.Enabled =
false
;
}

Now the last step
is
to write the timer's tick event to write the current time to the text file. Write the following code in your timer event:

private void timer1_Tick(object
sender, System.EventArgs e)
{
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.Flush();
}

Now use the Start and Stop buttons to start and stop the timer. The output mcb.txt file looks as in the following figure:



Using Timer control Programmatically

If you don't have Visual Studio .NET, you can also write the same sample. Just follow this procedure.

Creating an instance of Timer

The Timer class's constructor is used to create a timer object. The constructor is overloaded.

Public Timer()
Public Timer(
double
) Sets the interval property to the specified.

Here is
how to create a Timer with a 5 second interval.

Timer myTimer =
new
Timer(500);

Here are some useful members of the Timer class:

Tick This event occurs when the Interval has elapsed. 
Start Starts raising the Tick event by setting Enabled to true. 
Stop Stops raising the Tick event by setting Enabled to false. 
Close Releases the resources used by the Timer. 
AutoReset Indicates whether the Timer raises the Tick event each time the specified Interval has elapsed or whether the Tick event is raised only once after the first interval has elapsed.
Interval Indicates the interval on which to raise the Tick event.
Enabled Indicates whether the Timer raises the Tick event.

How to use the Timer class to raise an event after a certain interval?

The following code will use the Timer class to raise an event every 5 seconds:

timer1.Interval = 5000;
timer1.Enabled =
true
;
timer1.Tick +=
new
System.EventHandler (OnTimerEvent);

Write the event handler

This event will be executed every 5 seconds:

public static void OnTimerEvent(object
source, EventArgs e)
{
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.Flush();
}

You use Stop and Close events to stop the timer and release the resources. See the attached project for more details.

Up Next
    Ebook Download
    View all
    Learn
    View all