Timer (Clase)
Proporciona un mecanismo para ejecutar métodos en intervalos especificados. No se puede heredar esta clase.

Espacio de nombres: System.Threading
Ensamblado: mscorlib (en mscorlib.dll)

Sintaxis

Visual Basic (Declaración)
<ComVisibleAttribute(True)> _
Public NotInheritable Class Timer
    Inherits MarshalByRefObject
    Implements IDisposable
Visual Basic (Uso)
Dim instance As Timer
C#
[ComVisibleAttribute(true)] 
public sealed class Timer : MarshalByRefObject, IDisposable
C++
[ComVisibleAttribute(true)] 
public ref class Timer sealed : public MarshalByRefObject, IDisposable
J#
/** @attribute ComVisibleAttribute(true) */ 
public final class Timer extends MarshalByRefObject implements IDisposable
JScript
ComVisibleAttribute(true) 
public final class Timer extends MarshalByRefObject implements IDisposable
XAML
No aplicable.
Comentarios

NotaNota:

El atributo HostProtectionAttribute aplicado a esta clase tiene el valor de propiedad Resources siguiente: Synchronization | ExternalThreading. El atributo HostProtectionAttribute no afecta a las aplicaciones de escritorio (que normalmente se inician haciendo doble clic en un icono, escribiendo un comando o introduciendo una dirección URL en el explorador). Para obtener más información, vea la clase HostProtectionAttribute o Programación de SQL Server y atributos de protección del host.

Utilice un delegado de TimerCallback para especificar el método que desea que Timer ejecute. El delegado de temporizador se especifica cuando se construye el temporizador, y no se puede cambiar. El método no se ejecuta en el subproceso que creó el temporizador; se ejecuta en un subproceso ThreadPool suministrado por el sistema.

Cuando se crea un temporizador, se puede especificar un período de tiempo de espera antes de la primera ejecución del método (tiempo límite) y un período de tiempo de espera entre las ejecuciones posteriores (período). Puede cambiar estos valores, o deshabilitar el temporizador, utilizando el método Change.

NotaNota:

Siempre que se esté utilizando un Timer, se debe mantener una referencia a él. Como ocurre con cualquier objeto administrado, Timer será eliminado por el recolector de elementos no utilizados cuando no haya referencias a él. El hecho de que Timer siga estando activo no impide que los elimine el recolector de elementos no utilizados.

Si un temporizador deja de ser necesario, utilice el método Dispose para liberar los recursos controlados por el temporizador. Para recibir una señal cuando se deseche el temporizador, utilice la sobrecarga del método Dispose(WaitHandle) que admite un objeto WaitHandle. Una vez desechado el temporizador, se señala el objeto WaitHandle.

El método de devolución de llamada ejecutado por el temporizador debe ser de reentrada, porque se le llama en subprocesos de ThreadPool. La devolución de llamada se puede ejecutar simultáneamente en dos subprocesos del grupo de subprocesos si el intervalo del temporizador es menor que el tiempo necesario para ejecutar la devolución de llamada, o si todos los subprocesos del grupo de subprocesos están en uso y la devolución de llamada se sitúa varias veces en la cola.

NotaNota:

System.Threading.Timer es un temporizador sencillo y de pequeño tamaño que utiliza métodos de devolución de llamada, atendido por subprocesos del grupo de subprocesos. No se recomienda para su uso con formularios Windows Forms, porque no realiza las devoluciones de llamada en el subproceso de la interfaz de usuario. System.Windows.Forms.Timer es una opción más adecuada para el uso con formularios Windows Forms. Para la funcionalidad de temporizador basado en servidor, puede considerar la opción de utilizar System.Timers.Timer, que provoca eventos y tiene características adicionales.

Ejemplo

En el ejemplo de código siguiente se muestran las características de la clase Timer.

Visual Basic
Imports Microsoft.VisualBasic
Imports System
Imports System.Threading

Public Class TimerExample

    <MTAThread> _
    Shared Sub Main()
    
        Dim autoEvent As New AutoResetEvent(False)
        Dim statusChecker As New StatusChecker(10)

        ' Create the delegate that invokes methods for the timer.
        Dim timerDelegate As TimerCallback = _
            AddressOf statusChecker.CheckStatus

        ' Create a timer that signals the delegate to invoke 
        ' CheckStatus after one second, and every 1/4 second 
        ' thereafter.
        Console.WriteLine("{0} Creating timer." & vbCrLf, _
            DateTime.Now.ToString("h:mm:ss.fff"))
        Dim stateTimer As Timer = _
                New Timer(timerDelegate, autoEvent, 1000, 250)

        ' When autoEvent signals, change the period to every 
        ' 1/2 second.
        autoEvent.WaitOne(5000, False)
        stateTimer.Change(0, 500)
        Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)

        ' When autoEvent signals the second time, dispose of 
        ' the timer.
        autoEvent.WaitOne(5000, False)
        stateTimer.Dispose()
        Console.WriteLine(vbCrLf & "Destroying timer.")
    
    End Sub
End Class

Public Class StatusChecker

    Dim invokeCount, maxCount As Integer 

    Sub New(count As Integer)
        invokeCount  = 0
        maxCount = count
    End Sub

    ' This method is called by the timer delegate.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = _
            DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0} Checking status {1,2}.", _
            DateTime.Now.ToString("h:mm:ss.fff"), _
            invokeCount.ToString())

        If invokeCount = maxCount Then
        
            ' Reset the counter and signal to stop the timer.
            invokeCount  = 0
            autoEvent.Set()
        End If
    End Sub

End Class
C#
using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

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

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = 
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}
C++
using namespace System;
using namespace System::Threading;
ref class StatusChecker
{
private:
   int invokeCount;
   int maxCount;

public:
   StatusChecker( int count )
      : invokeCount( 0 ), maxCount( count )
   {}


   // This method is called by the timer delegate.
   void CheckStatus( Object^ stateInfo )
   {
      AutoResetEvent^ autoEvent = dynamic_cast<AutoResetEvent^>(stateInfo);
      Console::WriteLine( "{0} Checking status {1,2}.", DateTime::Now.ToString(  "h:mm:ss.fff" ), (++invokeCount).ToString() );
      if ( invokeCount == maxCount )
      {
         
         // Reset the counter and signal main.
         invokeCount = 0;
         autoEvent->Set();
      }
   }

};

int main()
{
   AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false );
   StatusChecker^ statusChecker = gcnew StatusChecker( 10 );
   
   // Create the delegate that invokes methods for the timer.
   TimerCallback^ timerDelegate = gcnew TimerCallback( statusChecker, &StatusChecker::CheckStatus );
   
   // Create a timer that signals the delegate to invoke CheckStatus 
   // after one second, and every 1/4 second thereafter.
   Console::WriteLine( "{0} Creating timer.\n", DateTime::Now.ToString(  "h:mm:ss.fff" ) );
   Timer^ stateTimer = gcnew Timer( timerDelegate,autoEvent,1000,250 );
   
   // When autoEvent signals, change the period to every 1/2 second.
   autoEvent->WaitOne( 5000, false );
   stateTimer->Change( 0, 500 );
   Console::WriteLine( "\nChanging period.\n" );
   
   // When autoEvent signals the second time, dispose of the timer.
   autoEvent->WaitOne( 5000, false );
   stateTimer->~Timer();
   Console::WriteLine( "\nDestroying timer." );
}
J#
import System.*;
import System.Threading.*;
import System.Threading.Thread;

class TimerExample
{
    public static void main(String[] args)
    {
        AutoResetEvent autoEvent = new AutoResetEvent(false);
        StatusChecker statusChecker = new StatusChecker(10);

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

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n",
            System.DateTime.get_Now().ToString("h:mm:ss.fff"));
        Timer stateTimer = new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    } //main
} //TimerExample

class StatusChecker
{
    private int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount = 0;
        maxCount = count;
    } //StatusChecker

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = ((AutoResetEvent)(stateInfo));

        Console.WriteLine("{0} Checking status {1,2}.", 
            System.DateTime.get_Now().ToString("h:mm:ss.fff"),
            String.valueOf(++invokeCount));
        if (invokeCount == maxCount) {
            // Reset the counter and signal Main.
            invokeCount = 0;
            autoEvent.Set();
        }
    } //CheckStatus
} //StatusChecker
Jerarquía de herencia

System.Object
   System.MarshalByRefObject
    System.Threading.Timer
Seguridad para subprocesos

Este tipo es seguro para la ejecución de subprocesos.

Plataformas

Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

Información de versión

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0

XNA Framework

Compatible con: 1.0
Vea también

Page view tracker