ARTICLE

Timer in C#

Posted by Mahesh Chand Articles | Multithreading in C# January 26, 2001
An article with sample project explains how to work with the Timer control in C# and .NET to write to a text file after few seconds.
Reader Level:
Download Files:
 

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.

Article Extensions
Contents added by Mahesh Chand on Sep 07, 2010
Download File: TimerSampleInCSharp.zip

Timer Control in Visual Studio 2010

A Timer control raises an event at a given interval of time without using a secondary thread. If you need to execute some code after certain interval of time continuously, you can use a timer control.

In this article, I will discuss how to create and use a Timer control in a Windows Forms application using Visual Studio 2010.

Timer Properties

Enabled property of timer represents if the timer is running. We can set this property to true to start a timer and false to stop a timer.

Interval property represents time on in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event. One second equals to 1000 milliseconds. So if you want a timer event to be fired every 5 seconds, you need to set Interval property to 5000.

Timer t = new Timer();

t.Interval = 2000;

timer1.Enabled = true;

Creating a Timer

A Timer control does not have a visual representation and works as a component in the background.

Design-time

You can create a timer at design-time by dragging and dropping a Timer component from Toolbox to a Form. After that, you can use F4 or right click Properties menu to set a Timer properties as shown in Figure 1. As you can see in Figure 1, the Enabled property is false and Interval is set to 1000 milliseconds (1 second).

TimerImg1.jpg
Figure 1

First thing you want to do is, change Enabled to true so the timer will start when your application starts.

Now next step is to add an event handler. If you go to the Events window by clicking little lightning icon, you will see only one Tick event as you can see from Figure 2. Double click on it will add the Tick event handler.

TimerImg2.jpg
Figure 2

The Tick event handler looks like following.

private void timer1_Tick(object sender, EventArgs e)

{

}

 

Now whatever code you write on this event handler, it will be executed every 1 second. For example, if you have a ListBox control on a Form and you want to add some items to it, the following code will do so.

private void timer1_Tick(object sender, EventArgs e)

{

    listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "," + DateTime.Now.ToLongDateString());

}

 

Run-time

Timer class represents a Timer control and used to create a Timer at run-time. The following code snippet creates a Timer at run-time, sets its property and event handler.

Timer t = new Timer();

t.Interval = 2000;

timer1.Enabled = true;

timer1.Tick += new System.EventHandler(OnTimerEvent);

 

The event handler code looks like following.

private void OnTimerEvent(object sender, EventArgs e)

{

    listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "," + DateTime.Now.ToLongDateString());

}

 

Summary

In this article, we discussed discuss how to create a Timer control in Windows Forms and set its various properties and events.

COMMENT USING