System.Threading.Timer Class

Assembly: Mscorlib.dll
Namespace: System.Threading
Summary
Provides a mechanism for executing methods at specified intervals. This class cannot be inherited.
C# Syntax:
public sealed class Timer : MarshalByRefObject, IDisposable
Remarks
Use a TimerCallback delegate to specify the methods associated with a Timer. The methods do not execute in the thread that created the timer; they execute in a separate thread that is automatically allocated by the system. The timer delegate is specified when the timer is constructed, and cannot be changed.

When creating a timer, the application specifies an amount of time to wait before the first invocation of the delegate methods (due time), and an amount of time to wait between subsequent invocations (period). 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.

When a timer is no longer needed, use the Timer.Dispose method to free the resources held by the timer.

Example
The following example demonstrates the features of the Timer class.
using System;
using System.Threading;

class TimerExampleState 
{
   public int counter = 0;
   public Timer tmr;
}

class App 
{
   public static void Main()
   {
   TimerExampleState s = new TimerExampleState();

   // Create the delegate that invokes methods for the timer.
   TimerCallback timerDelegate = new TimerCallback(CheckStatus);

   // Create a timer that waits one second, then invokes every second.
   Timer timer = new Timer(timerDelegate, s,1000, 1000);
    
   // Keep a handle to the timer, so it can be disposed.
   s.tmr = timer;

   // The main thread does nothing until the timer is disposed.
   while(s.tmr != null)
         Thread.Sleep(0);
   Console.WriteLine("Timer example done.");
   }
   // The following method is called by the timer's delegate.

   static void CheckStatus(Object state)
   {
   TimerExampleState s =(TimerExampleState)state;
   s.counter++;
   Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
   if(s.counter == 5)
      {
      // Shorten the period. Wait 10 seconds to restart the timer.
      (s.tmr).Change(10000,100);
      Console.WriteLine("changed...");
      }
   if(s.counter == 10)
      {
      Console.WriteLine("disposing of timer...");
      s.tmr.Dispose();
      s.tmr = null;
      }
   }
}

    

This code produces the following output (the exact timings returned will vary):

          				08:02:09.4811456 Checking Status 1. 
          				08:02:10.4825856 Checking Status 2. 
          				08:02:11.4840256 Checking Status 3. 
          				08:02:12.4854656 Checking Status 4. 
          				08:02:13.4869056 Checking Status 5. 
          				changed... 
          				08:02:23.4912912 Checking Status 6. 
          				08:02:23.5914352 Checking Status 7. 
          				08:02:23.6915792 Checking Status 8. 
          				08:02:23.7917232 Checking Status 9. 
          				08:02:23.8918672 Checking Status 10. 
          				disposing of timer... 
          				Timer example done.
          			
        
See also:
System.Threading Namespace | TimerCallback

System.Threading.Timer Member List:

Public Constructors
ctor #1 Overloaded:
.ctor(TimerCallback callback, object state, int dueTime, int period)

Initializes a new instance of the Timer class, using 32-bit signed integers to measure time intervals.
ctor #2 Overloaded:
.ctor(TimerCallback callback, object state, long dueTime, long period)

Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.
ctor #3 Overloaded:
.ctor(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)

Initializes a new instance of the Timer class, using TimeSpan values to measure time intervals.
ctor #4 Overloaded:
.ctor(TimerCallback callback, object state, uint dueTime, uint period)

Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.
Public Methods
Change Overloaded:
Change(int dueTime, int period)

Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.
Change Overloaded:
Change(long dueTime, long period)

Changes the start time and the interval between method invocations for a timer, using 64-bit signed integers to measure time intervals.
Change Overloaded:
Change(TimeSpan dueTime, TimeSpan period)

Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
Change Overloaded:
Change(uint dueTime, uint period)

Changes the start time and the interval between method invocations for a timer, using 32-bit unsigned integers to measure time intervals.
CreateObjRef
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.CreateObjRef


Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
Dispose Overloaded:
Dispose()

Releases all resources used by the current instance of Timer.
Dispose Overloaded:
Dispose(WaitHandle notifyObject)

Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.GetLifetimeService


Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InitializeLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.InitializeLifetimeService


Obtains a lifetime service object to control the lifetime policy for this instance.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize Overridden:
Releases the resources held by the current instance.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Threading.Timer Member Details

Overloaded ctor #1
Summary
Initializes a new instance of the Timer class, using 32-bit signed integers to measure time intervals.
C# Syntax:
public Timer(Timer(
   TimerCallback callback,
   object state,
   int dueTime,
   int period
);
Parameters:

callback

A TimerCallback delegate.

state

An object containing application-specific information relevant to the methods invoked by the callback parameter, or null.

dueTime

The amount of time to delay before callback invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.

period

The time interval between invocations of the methods referenced by callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException The dueTime or period parameter is negative and is not equal to Timeout.Infinite.
ArgumentNullException The callback parameter is null.
Remarks
The callback parameter invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), callback performs its first invocation immediately. If dueTime is Timeout.Infinite, callback does not invoke its methods. The timer is disabled, but it can be re-enabled using the Timer.Change method.

If period is zero (0) or Timeout.Infinite and dueTime is not Infinite, callback invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled using the Change method.

Return to top


Overloaded ctor #2
Summary
Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals.
C# Syntax:
public Timer(Timer(
   TimerCallback callback,
   object state,
   long dueTime,
   long period
);
Parameters:

callback

A TimerCallback delegate.

state

An object containing application-specific information relevant to the methods invoked by callback, or null.

dueTime

The amount of time to delay before callback invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.

period

The time interval between invocations of the methods referenced by callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException The dueTime or period parameter is negative and is not equal to Timeout.Infinite.
NotSupportedException The dueTime or period parameter is greater than 4294967294.
Remarks
The callback parameter invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), callback performs its first invocation immediately. If dueTime is Timeout.Infinite, callback does not invoke its methods. The timer is disabled, but it can be re-enabled using the Timer.Change method.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, callback invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled using the Change method.

Return to top


Overloaded ctor #3
Summary
Initializes a new instance of the Timer class, using TimeSpan values to measure time intervals.
C# Syntax:
public Timer(Timer(
   TimerCallback callback,
   object state,
   TimeSpan dueTime,
   TimeSpan period
);
Parameters:

callback

A TimerCallback delegate.

state

An object containing application-specific information relevant to the methods invoked by the callback parameter, or null.

dueTime

The TimeSpan representing the amount of time to delay before the callback parameter invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.

period

The time interval between invocations of the methods referenced by callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException The number of milliseconds in the value of dueTime or period is negative and not equal to Timeout.Infinite, or is greater than Int32.MaxValue.
ArgumentNullException The callback parameter is null.
Remarks
The callback parameter invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), callback performs its first invocation immediately. If dueTime is Timeout.Infinite, callback does not invoke its methods. The timer is disabled, but it can be re-enabled using the Timer.Change method.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, callback invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled using the Change method.

Return to top


Overloaded ctor #4
Summary
Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.
This member is not CLS Compliant

C# Syntax:
[CLSCompliant(false)]
public Timer(Timer(
   TimerCallback callback,
   object state,
   uint dueTime,
   uint period
);
Parameters:

callback

A TimerCallback delegate.

state

An object containing application-specific information relevant to the methods invoked by callback, or null.

dueTime

The amount of time to delay before callback invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.

period

The time interval between invocations of the methods referenced by callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Exceptions
Exception Type Condition
ArgumentOutOfRangeException The dueTime or period parameter is negative and is not equal to Timeout.Infinite.
ArgumentNullException The callback parameter is null.
Remarks
The callback parameter invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), callback performs its first invocation immediately. If dueTime is Timeout.Infinite, callback does not invoke its methods. The timer is disabled, but it can be re-enabled using the Timer.Change method.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, callback invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled using the Change method.

Return to top


Overloaded Method: Change(
   int dueTime,
   int period
)
Summary
Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.
C# Syntax:
public bool Change(
   int dueTime,
   int period
);
Parameters:

dueTime

The amount of time to delay before the delegate specified at Timer construction time invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.

period

The time interval between invocations of the methods referenced by the delegate specified at Timer construction time, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Return Value:
true if the current instance has not been disposed; otherwise, false.
Exceptions
Exception Type Condition
ArgumentOutOfRangeException The dueTime or period parameter is negative and is not equal to Timeout.Infinite.
Remarks
The delegate specified at Timer construction time invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), the delegate specified at Timer construction time performs its next invocation immediately. If dueTime is Timeout.Infinite, no methods are invoked. The timer is disabled, but it can be re-enabled by calling this method and specifying a positive value for dueTime.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, the delegate specified at Timer construction time invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled by specifying a positive value for period.

Return to top


Overloaded Method: Change(
   long dueTime,
   long period
)
Summary
Changes the start time and the interval between method invocations for a timer, using 64-bit signed integers to measure time intervals.
C# Syntax:
public bool Change(
   long dueTime,
   long period
);
Parameters:

dueTime

The amount of time to delay before the delegate specified at Timer construction time invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.

period

The time interval between invocations of the methods referenced by the delegate specified at Timer construction time, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Return Value:
true if the current instance has not been disposed; otherwise, false.
Exceptions
Exception Type Condition
ArgumentOutOfRangeException The dueTime or period parameter is less than -1.
NotSupportedException The dueTime or period parameter is greater than 4294967294.
Remarks
The delegate specified at Timer construction time invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), the delegate specified at Timer construction time performs its next invocation immediately. If dueTime is Timeout.Infinite, no methods are invoked. The timer is disabled, but it can be re-enabled by calling this method and specifying a positive value for dueTime.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, the delegate specified at Timer construction time invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled by specifying a positive value for period.

Return to top


Overloaded Method: Change(
   TimeSpan dueTime,
   TimeSpan period
)
Summary
Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
C# Syntax:
public bool Change(
   TimeSpan dueTime,
   TimeSpan period
);
Parameters:

dueTime

The TimeSpan representing the amount of time to delay before the callback parameter invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.

period

The time interval between invocations of the methods referenced by the delegate specified at Timer construction time, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Return Value:
true if the current instance has not been disposed; otherwise, false.
Remarks
The delegate specified at Timer construction time invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), the delegate specified at Timer construction time performs its next invocation immediately. If dueTime is Timeout.Infinite, no methods are invoked. The timer is disabled, but it can be re-enabled by calling this method and specifying a positive value for dueTime.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, the delegate specified at Timer construction time invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled by specifying a positive value for period.

Return to top


Overloaded Method: Change(
   uint dueTime,
   uint period
)
Summary
Changes the start time and the interval between method invocations for a timer, using 32-bit unsigned integers to measure time intervals.
This member is not CLS Compliant

C# Syntax:
[CLSCompliant(false)]
public bool Change(
   uint dueTime,
   uint period
);
Parameters:

dueTime

The amount of time to delay before the delegate specified at Timer construction time invokes its methods, in milliseconds. Specify Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.

period

The time interval between invocations of the methods referenced by the delegate specified at Timer construction time, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

Return Value:
true if the current instance has not been disposed; otherwise, false.
Remarks
The delegate specified at Timer construction time invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses.

If dueTime is zero (0), the delegate specified at Timer construction time performs its next invocation immediately. If dueTime is Timeout.Infinite, no methods are invoked. The timer is disabled, but it can be re-enabled by calling this method and specifying a positive value for dueTime.

If period is zero (0) or Timeout.Infinite, and dueTime is not Infinite, the delegate specified at Timer construction time invokes its methods once. The periodic behavior of the timer is disabled, but it can be re-enabled by specifying a positive value for period.

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Overloaded Method: Dispose()
Summary
Releases all resources used by the current instance of Timer.
C# Syntax:
public void Dispose();
Implements:
IDisposable.Dispose
Remarks
Calling Dispose allows the resources used by the Timer to be reallocated for other purposes. For more information about Dispose, see the conceptual topic at MSDN: cleaningupunmanagedresources.

Return to top


Overloaded Method: Dispose(
   WaitHandle notifyObject
)
Summary
Releases all resources used by the current instance of Timer and signals when the timer has been disposed of.
C# Syntax:
public bool Dispose(
   WaitHandle notifyObject
);
Parameters:

notifyObject

The WaitHandle to be signaled when the Timer has been disposed of.

Return Value:
true if the function succeeds; otherwise, false.
Exceptions
Exception Type Condition
NullReferenceException The notifyObject parameter is null.
Remarks
Calling Dispose allows the resources used by the Timer to be reallocated for other purposes. For more information about Dispose, see the conceptual topic at MSDN: cleaningupunmanagedresources.

When this method completes, it signals the WaitHandle specified by the notifyObject parameter. This method then calls GC.SuppressFinalize to prevent the garbage collector from calling the Finalize method.

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Finalize()
Summary
Releases the resources held by the current instance.
C# Syntax:
~Timer();
Remarks
Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see GC.SuppressFinalize and Object.Finalize.

This method overrides System.Object.Finalize.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: InitializeLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.InitializeLifetimeService

Summary
Obtains a lifetime service object to control the lifetime policy for this instance.
C# Syntax:
public virtual object InitializeLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the LifetimeServices.LeaseManagerPollTime property.
Remarks
For more information about lifetime services, see the LifetimeServices class.
Example
The following code example demonstrates creating a lease.
 public class MyClass : MarshalByRefObject
 {
   public override Object InitializeLifetimeService()
   {
     ILease lease = (ILease)base.InitializeLifetimeService();
     if (lease.CurrentState == LeaseState.Initial)
     {
          lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
          lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
           lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
     }
       return lease;
   }
 }

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.