3 out of 7 rated this helpful - Rate this topic

Timer Class

Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Windows.Forms.Timer

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)
public class Timer : Component

The Timer type exposes the following members.

  Name Description
Public method Timer() Initializes a new instance of the Timer class.
Public method Timer(IContainer) Initializes a new instance of the Timer class together with the specified container.
Top
  Name Description
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property Enabled Gets or sets whether the timer is running.
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property Interval Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Public property Tag Gets or sets an arbitrary string representing some type of user state.
Top
  Name Description
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Disposes of the resources, other than memory, used by the timer. (Overrides Component.Dispose(Boolean).)
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method OnTick Raises the Tick event.
Public method Start Starts the timer.
Public method Stop Stops the timer.
Public method ToString Infrastructure. Returns a string that represents the Timer. (Overrides Component.ToString().)
Top
  Name Description
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event Tick Occurs when the specified timer interval has elapsed and the timer is enabled.
Top

A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.

This class provides methods to set the interval, and to start and stop the timer.

Note Note

The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

The following example implements a simple interval timer, which sets off an alarm every five seconds. When the alarm occurs, a MessageBox displays a count of the number of times the alarm has started and prompts the user as to whether the timer should continue to run.


public class Class1 {
    static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    static int alarmCounter = 1;
    static bool exitFlag = false;

    // This is the method to run when the timer is raised.
    private static void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs) {
       myTimer.Stop();

       // Displays a message box asking whether to continue running the timer.
       if(MessageBox.Show("Continue running?", "Count is: " + alarmCounter, 
          MessageBoxButtons.YesNo) == DialogResult.Yes) {
          // Restarts the timer and increments the counter.
          alarmCounter +=1;
          myTimer.Enabled = true;
       }
       else {
          // Stops the timer.
          exitFlag = true;
       }
    }

    public static int Main() {
       /* Adds the event and the event handler for the method that will 
          process the timer event to the timer. */
       myTimer.Tick += new EventHandler(TimerEventProcessor);

       // Sets the timer interval to 5 seconds.
       myTimer.Interval = 5000;
       myTimer.Start();

       // Runs the timer, and raises the event.
       while(exitFlag == false) {
          // Processes all the events in the queue.
          Application.DoEvents();
       }
    return 0;
    }
 }
    


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Using the Interval as a Time Source
There are many posts, in many forums, that suggest something along the lines of;

You can count the number of seconds elapsed by setting the interval of the timer to 1000, and in the Tick event add 1 to a variable.  This small sample program requires a forms timer, a button, and 4 textboxes.  It illustrates why the interval is NOT a good time source.



Public Class Form1

    Private Sub Form1_Shown(sender As Object, _
                            e As System.EventArgs) Handles Me.Shown
        Timer1.Interval = 100 'tenth of a second
    End Sub

    Dim tmrIsRun As Boolean = False
    Dim stpw As New Stopwatch
    Dim tenths As Long = 0L

    Private Sub Timer1_Tick(sender As System.Object, _
                            e As System.EventArgs) Handles Timer1.Tick

        If tmrIsRun Then
            'show how much time has elapsed
            TextBox1.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", _
                                          stpw.Elapsed.Hours, _
                                          stpw.Elapsed.Minutes, _
                                          stpw.Elapsed.Seconds, _
                                          stpw.Elapsed.Milliseconds)

            'this illustrates why the timer interval
            'is a bad time source
            tenths += 1
            'show tenths.  Are they the same value?
            TextBox2.Text = (stpw.ElapsedMilliseconds / 100).ToString("n0")
            TextBox3.Text = tenths.ToString("n0")
            'show the variance
            TextBox4.Text = ((stpw.ElapsedMilliseconds / 100) - tenths).ToString("n0")
        End If
    End Sub

    Private Sub Button1_Click(sender As System.Object, _
                              e As System.EventArgs) Handles Button1.Click
        If tmrIsRun Then
            Timer1.Stop()
            stpw.Stop()
        Else
            Timer1.Start()
            stpw.Reset()
            stpw.Start()
            tenths = 0L
        End If
        tmrIsRun = Not tmrIsRun
    End Sub
End Class

Cross Thread Interval Timer
For generating timer events similar to js setInterval se DispatcherTimer Class
Windows.Forms.Timer For CE Windows Mobile
Plase take care if your want to start your timer yo should enable the timer and set interval in mili seconds

this sample is wron above it is up to windows application if your searching for Mobile

this is the designer code of timer in Mobile

            this.timer1.Enabled = true;
            this.timer1.Interval = 10000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

Rahmi Tuğrul altın