This documentation is archived and is not being maintained.

Timer Constructor (Double)

Initializes a new instance of the Timer class, and sets the Interval property to the specified number of milliseconds.

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

public:
Timer(
	double interval
)

Parameters

interval
Type: System::Double
The time, in milliseconds, between events. The value must be greater than zero and less than or equal to Int32::MaxValue.

ExceptionCondition
ArgumentException

The value of the interval parameter is less than or equal to zero, or greater than Int32::MaxValue.

This constructor sets the Interval property of the new timer instance, but does not enable the timer.

The following example creates a Timer that displays "Hello World!" on the console after ten seconds.

Use the System.Timers namespace for this example.


#using <system.dll>

using namespace System;
using namespace System::Timers;

public ref class Timer2
{
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 new Timer with Interval set to 10 seconds.
      aTimer = gcnew System::Timers::Timer( 10000 );

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

      // Only raise the event the first time Interval elapses.
      aTimer->AutoReset = false;
      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( "Hello World!" );
   }

};

int main()
{
   Timer2::Main();
}


.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.
Show: