Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

Timer classe

 

Date de publication : novembre 2016

Génère un événement au bout d'un intervalle défini, avec la possibilité de générer des événements récurrents.

Pour parcourir le code source de .NET Framework pour ce type, consultez la Source de référence.

Espace de noms:   System.Timers
Assembly:  System (dans System.dll)


[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public class Timer : Component, ISupportInitialize

NomDescription
System_CAPS_pubmethodTimer()

Initialise une nouvelle instance de la classe Timer et affecte à toutes les propriétés leurs valeurs initiales.

System_CAPS_pubmethodTimer(Double)

Initialise une nouvelle instance de la classe Timer et affecte le nombre spécifié de millisecondes à la propriété Interval.

NomDescription
System_CAPS_pubpropertyAutoReset

Obtient ou définit une valeur booléenne indiquant si Timer doit déclencher l'événement Elapsed une seule fois (false) ou de façon répétée (true).

System_CAPS_protpropertyCanRaiseEvents

Obtient une valeur indiquant si le composant peut déclencher un événement.(Hérité de Component.)

System_CAPS_pubpropertyContainer

Obtient les IContainer qui contient la Component.(Hérité de Component.)

System_CAPS_protpropertyDesignMode

Obtient une valeur qui indique si la Component est actuellement en mode design.(Hérité de Component.)

System_CAPS_pubpropertyEnabled

Obtient ou définit une valeur indiquant si Timer doit déclencher l'événement Elapsed.

System_CAPS_protpropertyEvents

Obtient la liste des gestionnaires d’événements associés à cette Component.(Hérité de Component.)

System_CAPS_pubpropertyInterval

Obtient ou définit l'intervalle, exprimé en millisecondes, auquel l'événement Elapsed doit être déclenché.

System_CAPS_pubpropertySite

Cette API prend en charge l’infrastructure de produit et n’est pas destinée à être utilisée directement depuis votre code. Obtient ou définit le site qui lie Timer à son conteneur en mode design.(Remplace Component.Site.)

System_CAPS_pubpropertySynchronizingObject

Obtient ou définit l'objet utilisé pour marshaler les appels du gestionnaire d'événements émis quand un intervalle a expiré.

NomDescription
System_CAPS_pubmethodBeginInit()

Débute l'initialisation au moment de l'exécution d'un Timer utilisé sur un formulaire ou par un autre composant.

System_CAPS_pubmethodClose()

Libère les ressources utilisées par le Timer.

System_CAPS_pubmethodCreateObjRef(Type)

Crée un objet qui contient toutes les informations requises pour générer un proxy permettant de communiquer avec un objet distant.(Hérité de MarshalByRefObject.)

System_CAPS_pubmethodDispose()

Libère toutes les ressources utilisées par Component.(Hérité de Component.)

System_CAPS_protmethodDispose(Boolean)

Cette API prend en charge l’infrastructure de produit et n’est pas destinée à être utilisée directement depuis votre code. Libère toutes les ressources utilisées par le Timer actuel.(Remplace Component.Dispose(Boolean).)

System_CAPS_pubmethodEndInit()

Met fin à l'initialisation au moment de l'exécution d'un Timer utilisé sur un formulaire ou par un autre composant.

System_CAPS_pubmethodEquals(Object)

Détermine si l'objet spécifié est identique à l'objet actuel.(Hérité de Object.)

System_CAPS_protmethodFinalize()

Libère les ressources non managées et exécute d'autres opérations de nettoyage avant la récupération du Component par le garbage collection.(Hérité de Component.)

System_CAPS_pubmethodGetHashCode()

Fait office de fonction de hachage par défaut.(Hérité de Object.)

System_CAPS_pubmethodGetLifetimeService()

Récupère l’objet de service de durée de vie actuelle qui contrôle la stratégie de durée de vie de cette instance.(Hérité de MarshalByRefObject.)

System_CAPS_protmethodGetService(Type)

Retourne un objet qui représente un service fourni par Component ou par son Container.(Hérité de Component.)

System_CAPS_pubmethodGetType()

Obtient le Type de l'instance actuelle.(Hérité de Object.)

System_CAPS_pubmethodInitializeLifetimeService()

Obtient un objet de service de durée de vie pour contrôler la stratégie de durée de vie de cette instance.(Hérité de MarshalByRefObject.)

System_CAPS_protmethodMemberwiseClone()

Crée une copie superficielle du Object actuel.(Hérité de Object.)

System_CAPS_protmethodMemberwiseClone(Boolean)

Crée une copie superficielle d’actuel MarshalByRefObject objet.(Hérité de MarshalByRefObject.)

System_CAPS_pubmethodStart()

Lance le déclenchement de l'événement Elapsed en affectant à Enabled la valeur true.

System_CAPS_pubmethodStop()

Arrête le déclenchement de l'événement Elapsed en affectant à Enabled la valeur false.

System_CAPS_pubmethodToString()

Retourne un String contenant le nom de la Component, le cas échéant. Cette méthode ne doit pas être remplacée.(Hérité de Component.)

NomDescription
System_CAPS_pubeventDisposed

Se produit lorsque le composant est supprimé par un appel à la Dispose (méthode).(Hérité de Component.)

System_CAPS_pubeventElapsed

Se produit quand l'intervalle est écoulé.

System_CAPS_noteRemarque

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_importantImportant

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_importantImportant

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).

using System;
using System.Threading.Tasks;
using System.Timers;

class Example
{
   static void Main()
   {
      Timer timer = new Timer(1000);
      timer.Elapsed += async ( sender, e ) => await HandleTimer();
      timer.Start();
      Console.Write("Press any key to exit... ");
      Console.ReadKey();
   }

   private static Task HandleTimer()
   {
     Console.WriteLine("\nHandler not implemented..." );
     throw new NotImplementedException();
   }
}
// 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.HandleTimer()
//      at Example.<<Main>b__0>d__2.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_noteRemarque

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_tipAstuce

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.

using System;
using System.Timers;

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

   public static void Main()
   {
      SetTimer();

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

      Console.WriteLine("Terminating the application...");
   }

   private static void SetTimer()
   {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }
}
// 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 depuis 1.1

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

Retour au début
Afficher: