Timer Control

Sometimes you may want to create a procedure that runs at certain times until a loop is finished or it runs when a set time interval is over. This process is possible with the Timer component.

In other words,

In C #, Timer repeatedly executes a coding block at a given time interval. The performance takes place via a timer. For instance, every 10 minutes to back up a folder or every second to write a log file. The method to be performed is placed in the timer case.

Sometimes we may want to create a procedure that runs at certain times until a loop is finished or it runs when a set time interval is over. This process is possible with the Timer component.

The timer class in C # is a timer. Windows Forms also has a timer control which can be placed into a Form and its properties are defined. In this example of code, we learn how to repeatedly write a timer to a texting file at a certain time interval in C#.

We can control programs in milliseconds, seconds, minutes and even hours with Timer Control. We can set Interval in milliseconds by Timer Control. This means that 1 second corresponds to one 1000 milliseconds. For instance, if we want to set a 1 minute interval, we set the value to 60000 at Interval, means 60x1000.

The Timer Control's Enabled property is False by default. So we need to set the Enabled property to Ture before executing the programme, and only the Timer Control will start its function.

Timer Control Property in C#

 

Example:

Windows app, which uses a timer to write text every 5 seconds into a text file. There are two buttons in our Windows Form app, start and stop. Once the Start button has clicked, the application writes a line into a text file every 1 second. After the Stop button is clicked, the application stops writing to the text file.

Step 1:

Open Visual Studio and create an application with Windows Forms.

Step2:

In the Form, add 2 button controls and name them Start and Stop. We have changed their names respectively to StartButton and StopButton. The form looks like the image below:

 

Timer Control C# Example 1

Step3:

Create a folder on C: drive and name it "My Temp", In "My Temp" folder create a text file and give a name my "my text file.txt" or "C:\\My Temp\\mytextfile.txt".

You should change your favorite name in this folder and file name.

 

Step 4:

Drag and drop the Timer controler from visual studio tool Box. This adds a Timer, name timer1 to the form. Now, we'll set the property of Timer. To open Properties, right click on the Timer control window. Set the property Interval to 1000.The value of the Interval property in milliseconds.

1 sec = 1000 milliseconds.

 

Step5:

Now, click on the Events button and double-click on the Tick property to add a Timer event handler. The Timer event is timer1_Tick. See below image:

Timer Control Event C#

Step 6:

At the beginning of the class, add a FileStream and a StreamWriter object. This class is used for creating a new text file and for writing to the text file. In the System.IO name space these classes are defined. So we import the name of System.IO at the top of the class.


using System.IO;

A file "my text file.txt" is created by the FileStream class and StreamWriter is used to write to the file.


  static FileStream fs = new FileStream(@"C:\My Temp\my text file.txt", FileMode.OpenOrCreate, FileAccess.Write);
        static StreamWriter m_streamWriter = new StreamWriter(fs);

Write in the following code on Form Load event,


  // To Write the file use StreamWriter class    
            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            streamWriter.Write(" File Write Operation Starts : ");
            streamWriter.WriteLine("{0} {1}",DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
            streamWriter.WriteLine("===================================== \n");
            streamWriter.Flush();

Now type code into the click handlers button Start and Stop. The last step is to write the tick event of the timer controler, to enter the current tick time in the text file.

 

Step 7

Build and Run the application.

To begin writing to text file, click on the Start button. Run for about a minute, click Stop to stop application.

The output "my text file.txt" looks like the image below.

 

Timer Control Output C#

 

Complete Source Code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TimerControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static FileStream fs = new FileStream(@"C:\My Temp\my text file.txt", FileMode.OpenOrCreate, FileAccess.Write);
        static StreamWriter streamWriter = new StreamWriter(fs);
        private void btnStart_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

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

        private void btnStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

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

 

Timer Control C#