C# Timer Control

What is C# Timer Control ?

The Timer Control plays an important role in the development of programs both Client side and Server side development as well as in Windows Services. With the Timer Control we can raise events at a specific interval of time without the interaction of another thread.

C# timer control

Use of Timer Control

We require Timer Object in many situations on our development environment. We have to use Timer Object when we want to set an interval between events, periodic checking, to start a process at a fixed time schedule, to increase or decrease the speed in an animation graphics with time schedule etc.

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

C# timer object

How to use C# Timer Control ?

We can control programs with Timer Control in millisecond , seconds, minutes and even in hours. The Timer Control allows us to set Interval property in milliseconds. That is, one second is equal to 1000 milliseconds. For example, if we want to set an interval of 1 minute we set the value at Interval property as 60000, means 60x1000 .

By default the Enabled property of Timer Control is False. So before running the program we have to set the Enabled property is True , then only the Timer Control starts its function.

C# timer property

C# Timer example

In the following program we display the current time in a Label Control. In order to develop this program, we need a Timer Control and a Label Control. Here we set the timer interval as 1000 milliseconds, that means one second, for displaying current system time in Label control for the interval of one second.

using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { label1.Text = DateTime.Now.ToString(); } } }

Start and Stop Timer Control

The Timer control have included the Start and Stop methods for start and stop the Timer control functions. The following C# program shows how to use a timer to write some text to a text file each seconds. The program has two buttons, Start and Stop. The application will write a line to a text file every 1 second once the Start button is clicked. The application stops writing to the text file once the Stop button is clicked.

Start and Stop C# Timer Control
using System; using System.Windows.Forms; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } TextWriter tsw; private void Form1_Load(object sender, EventArgs e) { tsw = new StreamWriter(@"D:\timer.txt", true); } private void timer1_Tick(object sender, EventArgs e) { label1.Text = DateTime.Now.ToString(); tsw.WriteLine(DateTime.Now.ToString()); } private void button1_Click(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Start(); } private void button2_Click(object sender, EventArgs e) { timer1.Stop(); tsw.Close(); } } }

Timer Tick Event

Timer Tick event occurs when the specified timer interval has elapsed and the timer is enabled.

myTimer.Tick += new EventHandler(TimerEventProcessor);

Timer Elapsed Event

Timer Elapsed event occurs when the interval elapses. The Elapsed event is raised if the Enabled property is true and the time interval (in milliseconds) defined by the Interval property elapses.

MyTimer.Elapsed += OnTimedEvent;

Timer Interval Property

Timer Interval property gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event .

// Sets the timer interval to 1 seconds. myTimer.Interval = 1000;

Timer Reset Property

Timer AutoReset property gets or sets a Boolean indicating whether the Timer should raise the Elapsed event only once (false) or repeatedly (true).

MyTimer.AutoReset = false;

TimerCallback Delegate

Callback represents the method that handles calls from a Timer. This method does not execute in the thread that created the timer; it executes in a separate thread pool thread that is provided by the system.

Timer Class

System.Timers.Timer fires an event at regular intervals . This is a somewhat more powerful timer. Instead of a Tick event, it has the Elapsed event. The Start and Stop methods of System.Timers.Timer which are similar to changing the Enabled property. Unlike the System.Windows.Forms.Timer, the events are effectively queued - the timer doesn't wait for one event to have completed before starting to wait again and then firing off the next event. The class is intended for use as a server-based or service component in a multithreaded environment and it has no user interface and is not visible at runtime.

The following example instantiates a System.Timers.Timer object that fires its Timer.Elapsed event every two seconds sets up an event handler for the event, and starts the timer.

  1. Create a timer object for one seconds interval.
myTimer = new System.Timers.Timer(1000);
  1. Set elapsed event for the timer. This occurs when the interval elapses.
myTimer.Elapsed += OnTimedEvent;
  1. Finally, start the timer.
myTimer.Enabled = true;

C# Timer (Console Application)

Working with a C# Timer class
using System; using System.Timers; namespace ConsoleApplication1 { class Program { private static System.Timers.Timer myTimer; static void Main(string[] args) { myTimer = new System.Timers.Timer(1000); myTimer.Elapsed += OnTimedEvent; myTimer.AutoReset = true; myTimer.Enabled = true; Console.WriteLine("\nPress Enter key to stop...\n"); Console.WriteLine("Timer started {0:HH:mm:ss.fff} ", DateTime.Now); Console.ReadLine(); myTimer.Stop(); myTimer.Dispose(); Console.WriteLine("Finished..."); } private static void OnTimedEvent(Object source, ElapsedEventArgs e) { Console.WriteLine("Elapsed event raised at {0:HH:mm:ss.fff}",e.SignalTime); } } }

Count down using C# Timer

The following C# program show how to cerate a seconds countdown using C# Timer.

Seconds CountDown C# Timer
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private System.Windows.Forms.Timer aTimer; private int counter = 60; private void button1_Click(object sender, EventArgs e) { aTimer = new System.Windows.Forms.Timer(); aTimer.Tick += new EventHandler(aTimer_Tick); aTimer.Interval = 1000; // 1 second aTimer.Start(); label1.Text = counter.ToString(); } private void aTimer_Tick(object sender, EventArgs e) { counter--; if (counter == 0) aTimer.Stop(); label1.Text = counter.ToString(); } } }

System.Threading.Timer Class

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

When creating a timer, the application specifies an amount of time to wait before the first invocation of the delegate methods , and an amount of time to wait between subsequent invocations. A timer invokes its methods when its due time elapses, and invokes its methods once per period thereafter. You can change these values, or you can disable the timer, by using the Timer.Change method.

using System; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { TimerState TS = new TimerState(); TimerCallback tDelegate = new TimerCallback(CheckStatus); Timer thisTimer = new Timer(tDelegate, TS, 1000, 1000); TS.tmr = thisTimer; while (TS.tmr != null) Thread.Sleep(0); Console.WriteLine("Finish !!"); Thread.Sleep(10000); } // The following method is called by the timer's delegate. static void CheckStatus(Object state) { TimerState TS = (TimerState)state; TS.counter++; Console.WriteLine("{0} Checking Status {1}.", DateTime.Now.TimeOfDay, TS.counter); if (TS.counter == 5) { (TS.tmr).Change(10000, 100); Console.WriteLine("changed..."); } if (TS.counter == 10) { Console.WriteLine("disposing of timer..."); TS.tmr.Dispose(); TS.tmr = null; } } } class TimerState { public int counter = 0; public Timer tmr; } }

Timer Threading in C#