How to Use Timer in C# (Tutorial with Sample Code) (2024)

C# Timer is used to implement a timer in C#. The Timer class in C# represents a Timer control that executes a code block repeatedly at a specified interval. For example, backing up a folder every 10 minutes or writing to a log file every second. The method that needs to be executed is placed inside the timer event.

Windows Forms has a Timer control that can be dropped to a Form and set its properties. Learn how to use a Timer in C# to write to a text file repeatedly at a certain time interval.

C# Timer Code Example

Let’s create a Windows application that will use a timer to write some text to a text file every 5 seconds. Our Windows Forms application has two buttons, Start and Stop. Once the Start button is clicked, the application will write a line to a text file every 1 second. The application stops writing to the text file after clicking the Stop button.

Step 1

Open Visual Studio and create a Windows Forms application.

Step 2

Add two Button controls to the Form and name them Start and Stop. You may also want to change their names. In my case, I have changed their names to StartButton and StopButton, respectively. The final Form looks like the following image.

How to Use Timer in C# (Tutorial with Sample Code) (1)

Note
We will create a text file, C:\temp\mcb.txt. Please change this folder and file name to the name you like. If you want to use the same name, please ensure you have a folder C:\temp on your computer.

Step 3

Now let’s add a Timer control to the Form. Drag and drop a Timer control from Visual Studio Toolbox to the Form. This will add a Timer control, timer1, to the Form.

Step 4

Now, we’re going to set Timer’s property.

Right-click on the Timer control and open the Properties window. Set the Interval property to 1000. The value of the Interval property is in milliseconds.

1 sec = 1000 milliseconds.

See below.

How to Use Timer in C# (Tutorial with Sample Code) (2)

Step 5

Now click the Events button and add a Timer event handler by double-clicking on the Tick property. The Timer event is timer1_Tick. See below.

How to Use Timer in C# (Tutorial with Sample Code) (3)

Step 6

Now I add a FileStream and a StreamWriter object at the beginning of the class. These classes are used to create a new text file and write to the text file.

The classes are defined in the System.IO namespace. Make sure to import the System.IO namespace at the top of the class.

usingSystem.IO;

As you can see from the following code, the FileStream class creates an mcb.txt file, and StreamWriter will be used to write to the file.

privatestaticFileStreamfs=newFileStream(@"c:\temp\mcb.txt",FileMode.OpenOrCreate,FileAccess.Write);privatestaticStreamWriterm_streamWriter=newStreamWriter(fs); 

Now write the following code in the Form Load event,

privatevoidForm1_Load(objectsender,System.EventArgse){//WritetothefileusingStreamWriterclassm_streamWriter.BaseStream.Seek(0,SeekOrigin.End);m_streamWriter.Write("FileWriteOperationStarts:");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, which stops executing the timer tick event.

privatevoidbutton1_Click(objectsender,System.EventArgse){ timer1. Enabled =true;}privatevoidbutton2_Click(objectsender,System.EventArgse){ 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,

privatevoidtimer1_Tick(objectsender,System.EventArgse){m_streamWriter.WriteLine("{0}{1}",DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());m_streamWriter.Flush();}

Step 7

Build and Run the application.

Click on the Start button to start writing to the text file. Run it for a minute or so, and click on the Stop button to stop it.

The output mcb.txt file looks like the following image.

How to Use Timer in C# (Tutorial with Sample Code) (4)

Using Timer at runtime in C #

We just saw how to use a Timer using Visual Studio designer at design time. But you may need to use a timer at run time.

The Timer class in C# represents a timer at runtime. Here are some useful members of the Timer class.

TickThis event occurs when the Interval has elapsed.
StartStarts raising the Tick event by setting Enabled to true.
StopStops raising the Tick event by setting Enabled to false.
CloseReleases the resources used by the Timer.
AutoResetIndicates 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.
IntervalIndicates the interval on which to raise the Tick event.
EnabledIndicates whether the Timer raises the Tick event.

The following code snippet creates a Timer at runtime, sets its property, and adds an event handler. In this code, we set Timer’s Interval to 2 seconds.

Timertimer1=newTimer{Interval=2000};timer1. Enabled = true;timer1. Tick += new System.EventHandler(OnTimerEvent);

Let’s say we want to display some text in a ListBox control. The following code adds text and updates the ListBox every 2 seconds.

privatevoidOnTimerEvent(objectsender,EventArgse){listBox1.Items.Add(DateTime.Now.ToLongTimeString()+","+DateTime.Now.ToLongDateString());}

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,

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

Write the event handler.

This event will be executed every 5 seconds,

publicstaticvoidOnTimerEvent(objectsource,EventArgse){m_streamWriter.WriteLine("{0}{1}",DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());m_streamWriter.Flush();}

Summary

This article discussed how to use a timer in C#. We also saw how to create a Windows application with a Timer control and use it to execute code at a certain interval of time.

How to Use Timer in C# (Tutorial with Sample Code) (2024)

References

Top Articles
Latest Posts
Article information

Author: Tish Haag

Last Updated:

Views: 5915

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.