Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Timer Class
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Timer Class

Updated: November 2007

Generates recurring events in an application.

Namespace:  System.Timers
Assembly:  System (in System.dll)

Visual Basic (Declaration)
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
    ExternalThreading := True)> _
Public Class Timer _
    Inherits Component _
    Implements ISupportInitialize
Visual Basic (Usage)
Dim instance As Timer
C#
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public class Timer : Component, ISupportInitialize
Visual C++
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public ref class Timer : public Component, 
    ISupportInitialize
J#
/** @attribute HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true) */
public class Timer extends Component implements ISupportInitialize
JScript
public class Timer extends Component implements ISupportInitialize
Note:

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time. For more information on server-based timers, see Introduction to Server-Based Timers.

The Timer component raises the Elapsed event, based on the value of the Interval property. You can handle this event to perform the processing you need. For example, suppose that you have an online sales application that continuously posts sales orders to a database. The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. You could use a Timer to start the batch processing every 30 minutes.

Note:

When AutoReset is set to false, the Timer raises the Elapsed event only once, after the first Interval has elapsed. To keep raising the Elapsed event on the Interval, set AutoReset to true.

In the .NET Framework version 2.0 and earlier, the Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. This behavior is subject to change in future releases of the .NET Framework.

The Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. Thus, the event handler should be reentrant.

Note:

The event-handling method might run on one thread at the same time that another thread calls the Stop method or sets the Enabled property to false. This might result in the Elapsed event being raised after the timer is stopped. The example code for the Stop method shows one way to avoid this race condition.

If you use the Timer with a user interface element, such as a form or control, assign the form or control that contains the Timer to the SynchronizingObject property, so that the event is marshaled to the user interface thread.

The Timer is not visible at run time.

For a list of initial property values for an instance of Timer, see the Timer constructor.

The following code example sets up an event handler for the Timer..::.Elapsed event, creates a timer, and starts the timer. The event handler displays the SignalTime property each time it is raised.

Visual Basic
Imports System
Imports System.Timers

Public Class Timer1

    Private Shared aTimer As System.Timers.Timer

    Public Shared Sub Main()
        ' Normally, the timer is declared at the class level,
        ' so that it stays in scope as long as it is needed.
        ' If the timer is declared in a long-running method,  
        ' KeepAlive must be used to prevent the JIT compiler 
        ' from allowing aggressive garbage collection to occur 
        ' before the method ends. (See end of method.)
        'Dim aTimer As System.Timers.Timer

        ' Create a timer with a ten second interval.
        aTimer = New System.Timers.Timer(10000)

        ' Hook up the Elapsed event for the timer.
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

        ' Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000
        aTimer.Enabled = True

        Console.WriteLine("Press the Enter key to exit the program.")
        Console.ReadLine()

        ' If the timer is declared in a long-running method, use
        ' KeepAlive to prevent garbage collection from occurring
        ' before the method ends.
        'GC.KeepAlive(aTimer)
    End Sub

    ' Specify what you want to happen when the Elapsed event is 
    ' raised.
    Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub
End Class

' This code example produces output similar to the following:
'
'Press the Enter key to exit the program.
'The Elapsed event was raised at 5/20/2007 8:42:27 PM
'The Elapsed event was raised at 5/20/2007 8:42:29 PM
'The Elapsed event was raised at 5/20/2007 8:42:31 PM
'...

C#
using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level,
        // so that it stays in scope as long as it is needed.
        // If the timer is declared in a long-running method,  
        // KeepAlive must be used to prevent the JIT compiler 
        // from allowing aggressive garbage collection to occur 
        // before the method ends. (See end of method.)
        //System.Timers.Timer aTimer;

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

Visual C++
#using <system.dll>

using namespace System;
using namespace System::Timers;

public ref class Timer1
{
private: 
   static System::Timers::Timer^ aTimer;

public:
   static void Demo()
   {
      // Normally, the timer is declared at the class level,
      // so that it stays in scope as long as it is needed.
      // If the timer is declared in a long-running method,  
      // KeepAlive must be used to prevent the JIT compiler 
      // from allowing aggressive garbage collection to occur 
      // before the method ends. (See end of method.)
      //System::Timers::Timer^ aTimer;

      // Create a new Timer with Interval set to 10 seconds.
      aTimer = gcnew System::Timers::Timer( 10000 );

      // Hook up the Elapsed event for the timer.
      aTimer->Elapsed += gcnew ElapsedEventHandler( Timer1::OnTimedEvent );

      // Set the Interval to 2 seconds (2000 milliseconds).
      aTimer->Interval = 2000;
      aTimer->Enabled = true;

      Console::WriteLine("Press the Enter key to exit the program.");
      Console::ReadLine();

      // If the timer is declared in a long-running method, use
      // KeepAlive to prevent garbage collection from occurring
      // before the method ends.
      //GC::KeepAlive(aTimer);
   }


private:
   // Specify what you want to happen when the Elapsed event is 
   // raised.
   static void OnTimedEvent( Object^ source, ElapsedEventArgs^ e )
   {
      Console::WriteLine( "The Elapsed event was raised at {0}", e->SignalTime );
   }

};

int main()
{
   Timer1::Demo();
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Timer Issues      ebonaba   |   Edit   |  
It seems that what's happening internally is that when the timer is set, .NET or the OS is adding the timer interval to the current count of milliseconds since reboot. If this happens to pass the Int.MaxValue threshold, it wraps back to start from zero, so the target time is incorrectly calculated to be BEFORE the current time. The timer fires immediately and keeps firing over and over again.

This problem occurs because of the mathematical error in a kernel timer manipulation. ISA Server uses a timer to monitor the Firewall service. Other applications that use a timer that is created by the CreateTimerQueueTimer function may also experience this issue.

Note The specified period should be less than 10 minutes.

This was a bug that was discovered when using the System.Timers.Timer.
Hot fix:

http://support.microsoft.com/?scid=kb%3Ben-us%3B944762&x=18&y=13

Make sure to Dispose this object      RandomEngy   |   Edit   |  
If you are making a lot of Timers that only fire once, take care to call Dispose() on them after you are finished. If you don't, garbage collection will never clean them up, even after their job has finished.

You can safely dispose of a Timer object inside the Elapsed event handler if you need to.


Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker