Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Clase Timer

 

Publicado: octubre de 2016

Genera un evento después de un intervalo establecido, con la opción de generar eventos recurrentes.

Para examinar el código fuente de .NET Framework de este tipo, consulte el origen de referencia.

Espacio de nombres:   System.Timers
Ensamblado:  System (en System.dll)


<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,
	ExternalThreading := True)>
Public Class Timer
	Inherits Component
	Implements ISupportInitialize

NombreDescripción
System_CAPS_pubmethodTimer()

Inicializa una nueva instancia de la clase Timer y establece todas las propiedades en sus valores iniciales.

System_CAPS_pubmethodTimer(Double)

Inicializa una nueva instancia de la clase Timer y establece la propiedad Interval en el número de milisegundos especificado.

NombreDescripción
System_CAPS_pubpropertyAutoReset

Obtiene o establece un valor booleano que indica si Timer debe generar el evento Elapsed solo una vez (false) o repetidamente (true).

System_CAPS_protpropertyCanRaiseEvents

Obtiene un valor que indica si el componente puede provocar un evento.(Heredado de Component).

System_CAPS_pubpropertyContainer

Obtiene IContainer que contiene Component.(Heredado de Component).

System_CAPS_protpropertyDesignMode

Obtiene un valor que indica si la Component está actualmente en modo de diseño.(Heredado de Component).

System_CAPS_pubpropertyEnabled

Obtiene o establece un valor que indica si Timer debe generar el evento Elapsed.

System_CAPS_protpropertyEvents

Obtiene la lista de controladores de eventos que se adjuntará a este Component.(Heredado de Component).

System_CAPS_pubpropertyInterval

Obtiene o establece el intervalo, expresado en milisegundos, en el que se generará el evento Elapsed.

System_CAPS_pubpropertySite

Esta API admite la infraestructura producto y no está diseñada para usarse directamente desde el código. Obtiene o establece el sitio que enlaza el objeto Timer a su contenedor en modo de diseño.(Invalida Component.Site).

System_CAPS_pubpropertySynchronizingObject

Obtiene o establece el objeto que se utiliza para calcular las referencias de las llamadas del controlador de eventos que se emiten al transcurrir un intervalo.

NombreDescripción
System_CAPS_pubmethodBeginInit()

Comienza la inicialización en tiempo de ejecución de un objeto Timer que se usa en un formulario o que lo usa otro componente.

System_CAPS_pubmethodClose()

Libera los recursos que usa Timer.

System_CAPS_pubmethodCreateObjRef(Type)

Crea un objeto que contiene toda la información pertinente necesaria para generar a un proxy utilizado para comunicarse con un objeto remoto.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodDispose()

Libera todos los recursos que usa Component.(Heredado de Component).

System_CAPS_protmethodDispose(Boolean)

Esta API admite la infraestructura producto y no está diseñada para usarse directamente desde el código. Libera todos los recursos que usa la clase Timer actual.(Invalida Component.Dispose(Boolean)).

System_CAPS_pubmethodEndInit()

Finaliza la inicialización en tiempo de ejecución de un objeto Timer que se usa en un formulario o que lo usa otro componente.

System_CAPS_pubmethodEquals(Object)

Determina si el objeto especificado es igual al objeto actual.(Heredado de Object).

System_CAPS_protmethodFinalize()

Libera recursos no administrados y realiza otras operaciones de limpieza antes de que se reclame el elemento Component durante la recolección de elementos no usados.(Heredado de Component).

System_CAPS_pubmethodGetHashCode()

Sirve como la función hash predeterminada.(Heredado de Object).

System_CAPS_pubmethodGetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.(Heredado de MarshalByRefObject).

System_CAPS_protmethodGetService(Type)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.(Heredado de Component).

System_CAPS_pubmethodGetType()

Obtiene el Type de la instancia actual.(Heredado de Object).

System_CAPS_pubmethodInitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.(Heredado de MarshalByRefObject).

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficial del Object actual.(Heredado de Object).

System_CAPS_protmethodMemberwiseClone(Boolean)

Crea una copia superficial del actual MarshalByRefObject objeto.(Heredado de MarshalByRefObject).

System_CAPS_pubmethodStart()

Empieza a generar el evento Elapsed al establecer Enabled en true.

System_CAPS_pubmethodStop()

Deja de generar el evento Elapsed al establecer Enabled en false.

System_CAPS_pubmethodToString()

Devuelve un String que contiene el nombre de la Component, si existe. Este método no se debe invalidar.(Heredado de Component).

NombreDescripción
System_CAPS_pubeventDisposed

Se produce cuando el componente se elimina mediante una llamada a la Dispose (método).(Heredado de Component).

System_CAPS_pubeventElapsed

Se produce cuando transcurre el intervalo.

System_CAPS_noteNota

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#System/services/timers/system/timers/Timer.cs#897683f27faba082. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The T:System.Timers.Timer component is a server-based timer that raises an E:System.Timers.Timer.Elapsed event in your application after the number of milliseconds in the P:System.Timers.Timer.Interval property has elapsed. You can configure the T:System.Timers.Timer object to raise the event just once or repeatedly using the P:System.Timers.Timer.AutoReset property. Typically, a T:System.Timers.Timer object is declared at the class level so that it stays in scope as long as it is needed. You can then handle its E:System.Timers.Timer.Elapsed 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 T:System.Timers.Timer object 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.

System_CAPS_importantImportante

The T:System.Timers.Timer class is available in the .NET Framework only. It is not included in the .NET Standard Library and is not available on other platforms, such as .NET Core or the Universal Windows Platform. On these platforms, as well as for portability across all .NET platforms, you should use the T:System.Threading.Timer class instead.

This type implements the T:System.IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

The server-based T:System.Timers.Timer class is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised E:System.Timers.Timer.Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

The T:System.Timers.Timer component raises the E:System.Timers.Timer.Elapsed event, based on the value (in milliseconds) of the P:System.Timers.Timer.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 T:System.Timers.Timer to start the batch processing every 30 minutes.

System_CAPS_importantImportante

The System.Timers.Timer class has the same resolution as the system clock. This means that the E:System.Timers.Timer.Elapsed event will fire at an interval defined by the resolution of the system clock if the P:System.Timers.Timer.Interval property is less than the resolution of the system clock. For more information, see the P:System.Timers.Timer.Interval property.

When P:System.Timers.Timer.AutoReset is set to false, a T:System.Timers.Timer object raises the E:System.Timers.Timer.Elapsed event only once, after the first P:System.Timers.Timer.Interval has elapsed. To keep raising the E:System.Timers.Timer.Elapsed event regularly at the interval defined by the P:System.Timers.Timer.Interval, set P:System.Timers.Timer.AutoReset to true, which is the default value.

The T:System.Timers.Timer component catches and suppresses all exceptions thrown by event handlers for the E:System.Timers.Timer.Elapsed event. This behavior is subject to change in future releases of the .NET Framework. Note, however, that this is not true of event handlers that execute asynchronously and include the await operator (in C#) or the Await operator (in Visual Basic). Exceptions thrown in these event handlers are propagated back to the calling thread, as the following example illustrates. For more information on exceptions thrown in asynchronous methods, see Exception Handling (Task Parallel Library).

Imports System.Threading.Tasks
Imports System.Timers

Public Module Example
   Public Sub Main()
      Dim timer As New Timer(1000)  
      AddHandler timer.Elapsed, AddressOf Example.HandleTimer     
      'timer.Elapsed = Async ( sender, e ) => await HandleTimer()
      timer.Start()
      Console.Write("Press any key to exit... ")
      Console.ReadKey()
   End Sub

   Private Async Sub HandleTimer(sender As Object, e As EventArgs)
      Await Task.Run(Sub()
                        Console.WriteLine()
                        Console.WriteLine("Handler not implemented..." )
                        Throw New NotImplementedException()
                     End Sub)   
   End Sub
End Module
' The example displays output like the following:
'   Press any key to exit...
'   Handler not implemented...
'   
'   Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
'      at Example._Lambda$__1()
'      at System.Threading.Tasks.Task.Execute()
'   --- End of stack trace from previous location where exception was thrown ---
'      at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
'      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
'      at Example.VB$StateMachine_0_HandleTimer.MoveNext()
'   --- End of stack trace from previous location where exception was thrown ---
'      at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
'      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
'      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
'      at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
'      at System.Threading.ThreadPoolWorkQueue.Dispatch()

If the P:System.Timers.Timer.SynchronizingObject property is null, the E:System.Timers.Timer.Elapsed event is raised on a T:System.Threading.ThreadPool thread. If processing of the E:System.Timers.Timer.Elapsed event lasts longer than P:System.Timers.Timer.Interval, the event might be raised again on another T:System.Threading.ThreadPool thread. In this situation, the event handler should be reentrant.

System_CAPS_noteNota

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

Even if P:System.Timers.Timer.SynchronizingObject is not null, E:System.Timers.Timer.Elapsed events can occur after the Overload:System.Timers.Timer.Dispose or M:System.Timers.Timer.Stop method has been called or after the P:System.Timers.Timer.Enabled property has been set to false, because the signal to raise the E:System.Timers.Timer.Elapsed event is always queued for execution on a thread pool thread. One way to resolve this race condition is to set a flag that tells the event handler for the E:System.Timers.Timer.Elapsed event to ignore subsequent events.

If you use the T:System.Timers.Timer class with a user interface element, such as a form or control, without placing the timer on that user interface element, assign the form or control that contains the T:System.Timers.Timer to the P:System.Timers.Timer.SynchronizingObject property, so that the event is marshaled to the user interface thread.

For a list of default property values for an instance of T:System.Timers.Timer, see the M:System.Timers.Timer.#ctor constructor.

System_CAPS_tipSugerencia

Be aware that the .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer (this topic): fires an event at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Threading.Timer: executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.

  • System.Windows.Forms.Timer: a Windows Forms component that fires an event at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.

  • System.Web.UI.Timer: an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

The following example instantiates a System.Timers.Timer object that fires its E:System.Timers.Timer.Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the event, and starts the timer. The event handler displays the value of the P:System.Timers.ElapsedEventArgs.SignalTime property each time it is raised.

Imports System.Timers

Public Module Example
    Private aTimer As System.Timers.Timer

    Public Sub Main()
        SetTimer()

      Console.WriteLine("{0}Press the Enter key to exit the application...{0}",
                        vbCrLf)
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}",
                        DateTime.Now)
      Console.ReadLine()
      aTimer.Stop()
      aTimer.Dispose()

      Console.WriteLine("Terminating the application...")
    End Sub

    Private Sub SetTimer()
        ' Create a timer with a two second interval.
        aTimer = New System.Timers.Timer(2000)
        ' Hook up the Elapsed event for the timer. 
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
        aTimer.AutoReset = True
        aTimer.Enabled = True
    End Sub

    ' The event handler for the Timer.Elapsed event. 
    Private Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime)
    End Sub 
End Module
' The example displays output like the following:
'       Press the Enter key to exit the application...
'
'       The application started at 09:40:29.068
'       The Elapsed event was raised at 09:40:31.084
'       The Elapsed event was raised at 09:40:33.100
'       The Elapsed event was raised at 09:40:35.100
'       The Elapsed event was raised at 09:40:37.116
'       The Elapsed event was raised at 09:40:39.116
'       The Elapsed event was raised at 09:40:41.117
'       The Elapsed event was raised at 09:40:43.132
'       The Elapsed event was raised at 09:40:45.133
'       The Elapsed event was raised at 09:40:47.148
'
'       Terminating the application...

.NET Framework
Disponible desde 1.1

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

Volver al principio
Mostrar: