You are on page 1of 9

A timer is a specialized type of clock.

A timer can be used to control the sequence of an


event or process. Whereas a stopwatch counts upwards from zero for measuring elapsed
time, a timer counts down from a specified time interval, like an hourglass.

A simple digital timer. The internal components—including the circuit board with control
chip and LED display, a battery, and a buzzer—are visible.

Timers can be mechanical, electromechanical, electronic (quartz), or even software as


most computers include digital timers of one kind or another.

Mechanical Timers
Early mechanical timers used typical clockwork mechanisms, such as an escapement and
spring to regulate their speed. Inaccurate, cheap mechanisms use a flat beater that spins
against air resistance. Mechanical egg-timers are usually of this type.

More accurate mechanisms resemble small alarm clocks, with the chief advantage being
that they require little battery/electrical power, and can be stored for long periods of time.
The most widely-known application is to control explosives.

[edit] Electromechanical timers


There are two types of electromechanical timers. A thermal type has a metal finger made
of strips of two metals with different rates of thermal expansion sandwiched together;
steel and bronze are common. An electric current flowing through this finger causes
heating of the metals, one side expands less than the other, and an electrical contact on
the end of the finger moves away from or towards an electrical switch contact. The most
common use of this type is in the "flasher" units that flash turn signals in automobiles,
and sometimes in Christmas lights.

Another type of electromechanical timer (a cam timer) uses a small synchronous AC


motor turning a cam against a comb of switch contacts. The AC motor is turned at an
accurate rate by the alternating current, which power companies carefully regulate. Gears
slow this motor down to the desired rate, and turn the cam. The most common application
of this timer now is in washers, driers and dishwashers. This type of timer often has a
friction clutch between the gear train and the cam, so that the cam can be turned to reset
the time.

Electromechanical timers survive in these applications because mechanical switch


contacts are still less expensive than the semiconductor devices needed to control
powerful lights, motors and heaters.

In the past these electromechanical timers were often combined with electrical relays to
create electro-mechanical controllers. Electromechanical timers reached a high state of
development in the 1950s and 60s because of their extensive use in aerospace and
weapons systems. Programmable electromechanical timers controlled launch sequence
events in early rockets and ballistic missiles.

[edit] Electronic Timers


Electronic timers can achieve higher precision than mechanical timers because they are
quartz clocks with special electronics. Electronic timers can be analog (resembling a
mechanical timer) or digital (uses a display much like a digital clock). Integrated circuits
have made digital logic so inexpensive that an electronic timer is now less expensive than
many mechanical and electromechanical timers. Individual timers are implemented as a
simple single-chip computer system, similar to a watch. Watch technology is used in
these devices.

However, most timers are now implemented in software. Modern controllers use a
programmable logic controller rather than a box full of electromechanical parts. The logic
is usually designed as if it were relays, using a special computer language called ladder
logic. In PLCs, timers are usually simulated by the software built into the controller. Each
timer is just an entry in a table maintained by the software.

Digital timers can also be used in safety device such as a Gas Timer.

[edit] Computer timers


Computer systems usually have at least one timer. These are typically digital counters
that either increment or decrement at a fixed frequency, which is often configurable, and
that interrupt the processor when reaching zero, or a counter with a sufficiently large
word size that it will not reach its counter limit before the end of life of the system.

More sophisticated timers may have comparison logic to compare the timer value against
a specific value, set by software, that triggers some action when the timer value matches
the preset value. This might be used, for example, to measure events or generate pulse
width modulated waveforms to control the speed of motors (using a class D digital
electronic amplifier.

As the number of hardware timers in a computer system or processor is finite and limited,
operating systems and embedded systems often use a single hardware timer to implement
an extensible set of software timers. In this scenario, the hardware timer's interrupt
service routine would handle house-keeping and management of as many software timers
as are required, and the hardware timer would be set to expire when the next software
timer is due to expire. At expiry, the interrupt routine would update the hardware timer to
expire when the next software timer is due, and any actions would be triggered for the
software timers that had just expired. Expired timers that are continuous would also be
reset to a new expiry time based on their timer interval, and one-shot timers would be
disabled or removed from the set of timers. While simple in concept, care must be taken
with software timer implementation if issues such as timer drift and delayed interrupts is
to be minimised.

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

Using 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.

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

Using 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 interval. Stop button stops the timer and
Start again start the timer.

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 Toolbox of
Visual Studio. You can set timer properties from the IDE as well as programmatically.
To set the timer properties, right click on the timer control and change Interval
property. As you can see from the Figure,

I put 5000 milliseconds (5 seconds).

1 sec = 1000 milliseconds.


Now click on the Events button and write 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, 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 on 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 timer's Enabled property as true. Setting
timer's Enabled property starts timer to execute the timer event. I set Enabled
property as false on the Stop button click event handler, which 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 last step is to write timer's tick event to write current time to the text file. Write
the following code on 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 Start and Stop buttons to start and stop the timer. The output mcb.txt file
looks like the following figure.
Using Timer control Programmatically

If you don't have Visual Studio .NET, you can also write the same sample. Just
following these steps.

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 5 seconds 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 Timer class to raise an event after certain interval?

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

Write the event handler

This event will be executed after every 5 secs.

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
attached project for more details.

Working with a Timer in C#


By Bradley L. Jones

This article is an excerpt from the book Sams Teach Yourself the C# Language in 21
Days.

The following listing presents a neat little program that is not well designed. It is
simple, and there is nothing complex presented in it. It simply prints the time to the
console. Forever.

Listing 1. timer.cs - Displaying the time.

1: // Timer01.cs - Displaying Date and Time


2: // Not a great way to do the time.
3: // Press Ctrl+C to end program.
4: //------------------------------------------
5: using System;
6:
7: class myApp
8: {
9: public static void Main()
10: {
11: while (true)
12: {
13: Console.Write("r{0}", DateTime.Now);
14: }
15: }
16: }

*** Output ***

5/26/2003 9:34:19 PM

*** Analysis ***

As you can see, this listing was executed at 9:34 on May the 26th. This listing
presents a clock on the command line. This clock seems to update the time every
second. Actually it us updating much more often than that; however, you only notice
the changes every second when the value being displayed actually changes. This
program runs until you break out of it using Ctrl+C.

In line 13, a call to DateTime is made. DateTime is a structure that is available from
the System namespace within the base class libraries. This structure has a static
method called Now that returns the current time. There are a large number of
additional data members and methods within the DateTime structure. You can
check out the .NET Framework class library documentation for information on these.
There are also a few other aritcles here on CodeGuru.com

A better way to present a date on the screen is with a timer. A timer allows a
process—in the form of a delegate—to be called at a specific time or after a specific
period of time has passed. The framework includes a class for timers within the
System.Timers namespace. This class is appropriately called Timer. Listing 2 is a
rewrite of listing 1 using a Timer.

Listing 2. Timer02.cs - Using a timer with the DateTime.

1: // Timer02.cs - Displaying Date and Time


2: // Using the Timer class.
3: // Press Ctrl+C to end program.
4: //------------------------------------------
5: using System;
6: using System.Timers;
7:
8: class myApp
9: {
10: public static void Main()
11: {
12: Timer myTimer = new Timer();
13: myTimer.Elapsed += new ElapsedEventHandler( DisplayTimeEvent );
14: myTimer.Interval = 1000;
15: myTimer.Start();
16:
17: while ( Console.Read() != 'q' )
18: {
19: ; // do nothing...
20: }
21: }
22:
23: public static void DisplayTimeEvent( object source, ElapsedEventArgs e )
24: {
25: Console.Write("\r{0}", DateTime.Now);
26: }
27: }

*** Output ***

5/26/2003 10:04:13 PM

*** Analysis ***

As you can see, this listing's output is just like that of the previous listing. This
listing, however, operates much better. Instead of constantly updating the date and
time being displayed, this listing only updates it every 1000 ticks. 1000 ticks is equal
to one second.
Looking closer at this listing, you can see how a Timer works. In line 12 a new Timer
object is created. In line 14 the interval that is to be used is set. In line 13 the
method that is to be executed after the interval is associated to the timer. In this
case, the DisplayTimeEvent will be executed. This method is defined in lines 23 to
26.

In line 15 the Start method is called this will start the interval. Another member for
the Timer class is the AutoReset member. If you change the default value from
true to false, then the Timer event will happen only once. If the AutoReset is left
at its default value of true, or set to true, then the Timer will fire an event and thus
execute the method every time the given interval passes.

Line 17 to 20 contain a loop that continues to operate until the reader enters the
letter 'q' and presses enter. Once the user does this, the end of the routine is
reached and the program ends; otherwise, the program continues to spin in this
loop. Nothing is done in this loop in this program. You can do other processing in this
loop if you desired. There is no need to call the DisplayTimeEvent in this loop
because it will be automatically called at the appropriate interval.

This timer is used to display the time on the screen. Timer and timer events can be
used for numerous other programs as well. You could create a timer that fires off a
program at a given time. You could create a backup routine that copies important
data at a given interval. You could create a routine to automatically log off a user or
end a program after a given time period with no activity. There are numerous ways
to use timers.

This article is brought to you by Sams Publishing and Bradley L.


Jones.
Sams Teach Yourself the C# Language in 21 Days
© Copyright Bradley