Timer.Interval Timer.Interval Timer.Interval Timer.Interval Property

Definição

Obtém ou define o intervalo, expressado em milissegundos, no qual gerar o evento Elapsed.Gets or sets the interval, expressed in milliseconds, at which to raise the Elapsed event.

public:
 property double Interval { double get(); void set(double value); };
[System.ComponentModel.SettingsBindable(true)]
[System.Timers.TimersDescription("The number of milliseconds between timer events.")]
[System.Timers.TimersDescription("TimerInterval")]
public double Interval { get; set; }
member this.Interval : double with get, set
Public Property Interval As Double

Valor da propriedade

O tempo, em milissegundos, entre eventos Elapsed.The time, in milliseconds, between Elapsed events. O valor deve ser maior que zero e menor ou igual a MaxValue.The value must be greater than zero, and less than or equal to MaxValue. O padrão é 100 milissegundos.The default is 100 milliseconds.

Exceções

O intervalo é menor ou igual a zero.The interval is less than or equal to zero.

- ou --or- O intervalo é maior que MaxValue e o timer está habilitado no momento.The interval is greater than MaxValue, and the timer is currently enabled. (Se o timer não estiver habilitado no momento, nenhuma exceção será lançada até que ele seja habilitado.)(If the timer is not currently enabled, no exception is thrown until it becomes enabled.)

Exemplos

O exemplo a seguir instancia um Timer objeto que aciona seu Timer.Elapsed eventos a cada dois segundos (2000 milissegundos), configura um manipulador de eventos para o evento e inicia o temporizador.The following example instantiates a Timer object that fires its Timer.Elapsed event every two seconds (2000 milliseconds), sets up an event handler for the event, and starts the timer. O manipulador de eventos exibe o valor da ElapsedEventArgs.SignalTime propriedade cada vez que ele é acionado.The event handler displays the value of the ElapsedEventArgs.SignalTime property each time it is raised.

using namespace System;
using namespace System::Timers;

public ref class Example
{
private:
    static System::Timers::Timer^ aTimer;

public:
    static void Demo()
    {
        // Create a timer and set a two second interval.
        aTimer = gcnew System::Timers::Timer();
        aTimer->Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer->Elapsed += gcnew System::Timers::ElapsedEventHandler(Example::OnTimedEvent);

        // Have the timer fire repeated events (true is the default)
        aTimer->AutoReset = true;

        // Start the timer
        aTimer->Enabled = true;

        Console::WriteLine("Press the Enter key to exit the program at any time... ");
        Console::ReadLine();
    }

private:
    static void OnTimedEvent(Object^ source, System::Timers::ElapsedEventArgs^ e)
    {
        Console::WriteLine("The Elapsed event was raised at {0}", e->SignalTime);
    }
};

int main()
{
    Example::Demo();
}
// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM 

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM 
Imports System.Timers

Public Module Example
    Private aTimer As Timer

    Public Sub Main()
        ' Create a timer and set a two second interval.
        aTimer = New System.Timers.Timer()
        aTimer.Interval = 2000

        ' Hook up the Elapsed event for the timer.  
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

        ' Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = True

        ' Start the timer
        aTimer.Enabled = True

        Console.WriteLine("Press the Enter key to exit the program at any time... ")
        Console.ReadLine()
    End Sub

    Private Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub
End Module
' The example displays output like the following: 
'       Press the Enter key to exit the program at any time... 
'       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:06 PM 

Comentários

Você usa o Interval propriedade para determinar a frequência na qual o Elapsed evento é disparado.You use the Interval property to determine the frequency at which the Elapsed event is fired. Porque o Timer classe depende do relógio do sistema, ele tem a mesma resolução do relógio do sistema.Because the Timer class depends on the system clock, it has the same resolution as the system clock. Isso significa que o Elapsed evento será acionado em um intervalo definido pela resolução do relógio do sistema se o Interval propriedade é menor que a resolução do relógio do sistema.This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock. O exemplo a seguir define o Interval propriedade para 5 milissegundos.The following example sets the Interval property to 5 milliseconds. Quando executado em um Windows 7Windows 7 sistema cujo relógio do sistema tem uma resolução de aproximadamente 15 milissegundos, o evento é acionado, aproximadamente a cada 15 milissegundos, em vez da cada 5 milissegundos.When run on a Windows 7Windows 7 system whose system clock has a resolution of approximately 15 milliseconds, the event fires approximately every 15 milliseconds rather than every 5 milliseconds.

using System;
using System.IO;
using System.Collections.Generic;
using System.Timers;

public class Example
{
   private static Timer aTimer;
   private static List<String> eventlog;
   private static int nEventsFired = 0;
   private static DateTime previousTime;
       
   public static void Main()
   {
        eventlog = new List<String>();
        
        StreamWriter sr = new StreamWriter(@".\Interval.txt");
        // Create a timer with a five millisecond interval.
        aTimer = new Timer(5);
        aTimer.Elapsed += OnTimedEvent;
        // Hook up the Elapsed event for the timer. 
        aTimer.AutoReset = true;
        sr.WriteLine("The timer should fire every {0} milliseconds.", 
                     aTimer.Interval);
        aTimer.Enabled = true;

        
        Console.WriteLine("Press the Enter key to exit the program... ");
        Console.ReadLine();
        foreach (var item in eventlog)
           sr.WriteLine(item);
        sr.Close();
        Console.WriteLine("Terminating the application...");
   }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        eventlog.Add(String.Format("Elapsed event at {0:HH':'mm':'ss.ffffff} ({1})", 
                                   e.SignalTime, 
                                   nEventsFired++ == 0 ? 
                                      0.0 : (e.SignalTime - previousTime).TotalMilliseconds));
        previousTime = e.SignalTime;
        if (nEventsFired == 20) {
           Console.WriteLine("No more events will fire...");
           aTimer.Enabled = false;
        }
    }
}
// The example writes output like the following to a file:
//       The timer should fire every 5 milliseconds.
//       Elapsed event at 08:42:49.370344 (0)
//       Elapsed event at 08:42:49.385345 (15.0015)
//       Elapsed event at 08:42:49.400347 (15.0015)
//       Elapsed event at 08:42:49.415348 (15.0015)
//       Elapsed event at 08:42:49.430350 (15.0015)
//       Elapsed event at 08:42:49.445351 (15.0015)
//       Elapsed event at 08:42:49.465353 (20.002)
//       Elapsed event at 08:42:49.480355 (15.0015)
//       Elapsed event at 08:42:49.495356 (15.0015)
//       Elapsed event at 08:42:49.510358 (15.0015)
//       Elapsed event at 08:42:49.525359 (15.0015)
//       Elapsed event at 08:42:49.540361 (15.0015)
//       Elapsed event at 08:42:49.555362 (15.0015)
//       Elapsed event at 08:42:49.570364 (15.0015)
//       Elapsed event at 08:42:49.585365 (15.0015)
//       Elapsed event at 08:42:49.605367 (20.002)
//       Elapsed event at 08:42:49.620369 (15.0015)
//       Elapsed event at 08:42:49.635370 (15.0015)
//       Elapsed event at 08:42:49.650372 (15.0015)
//       Elapsed event at 08:42:49.665373 (15.0015)
Imports System.Collections.Generic
Imports System.IO
Imports System.Timers

Module Example
   Private WithEvents aTimer As Timer
   Private eventlog As List(Of String)
   Private nEventsFired As Integer = 0
   Private previousTime As Date

   Public Sub Main()
        eventlog = New List(Of String)()
        
        Dim sr As New StreamWriter(".\Interval.txt")
        ' Create a timer with a five millisecond interval.
        aTimer = New Timer(5)
        aTimer.AutoReset = True
        sr.WriteLine("The timer should fire every {0} milliseconds.", 
                     aTimer.Interval)
        aTimer.Enabled = True

        
        Console.WriteLine("Press the Enter key to exit the program... ")
        Console.ReadLine()
        For Each item In eventlog
           sr.WriteLine(item)
        Next
        sr.Close()
        Console.WriteLine("Terminating the application...")
   End Sub

    Private Sub OnTimedEvent(source As Object, e As ElapsedEventArgs) _
                             Handles aTimer.Elapsed
        eventlog.Add(String.Format("Elapsed event at {0:HH':'mm':'ss.ffffff} ({1})", 
                                   e.SignalTime, 
                                   If(nEventsFired = 0, 
                                      0.0, (e.SignalTime - previousTime).TotalMilliseconds)))
        nEventsFired += 1
        previousTime = e.SignalTime
        if nEventsFired = 20 Then
           Console.WriteLine("No more events will fire...")
           aTimer.Enabled = False
        End If
   End Sub
End Module
' The example displays the following output:
'       The timer should fire every 5 milliseconds.
'       Elapsed event at 08:42:49.370344 (0)
'       Elapsed event at 08:42:49.385345 (15.0015)
'       Elapsed event at 08:42:49.400347 (15.0015)
'       Elapsed event at 08:42:49.415348 (15.0015)
'       Elapsed event at 08:42:49.430350 (15.0015)
'       Elapsed event at 08:42:49.445351 (15.0015)
'       Elapsed event at 08:42:49.465353 (20.002)
'       Elapsed event at 08:42:49.480355 (15.0015)
'       Elapsed event at 08:42:49.495356 (15.0015)
'       Elapsed event at 08:42:49.510358 (15.0015)
'       Elapsed event at 08:42:49.525359 (15.0015)
'       Elapsed event at 08:42:49.540361 (15.0015)
'       Elapsed event at 08:42:49.555362 (15.0015)
'       Elapsed event at 08:42:49.570364 (15.0015)
'       Elapsed event at 08:42:49.585365 (15.0015)
'       Elapsed event at 08:42:49.605367 (20.002)
'       Elapsed event at 08:42:49.620369 (15.0015)
'       Elapsed event at 08:42:49.635370 (15.0015)
'       Elapsed event at 08:42:49.650372 (15.0015)
'       Elapsed event at 08:42:49.665373 (15.0015)

Você pode usar o código a seguir para determinar a resolução do relógio do sistema no sistema atual:You can use the following code to determine the resolution of the system clock on the current system:

using System;
using System.Runtime.InteropServices;

public class Example
{
   [DllImport("kernel32.dll", SetLastError=true)]
   static extern bool GetSystemTimeAdjustment(out long lpTimeAdjustment,
                                              out long lpTimeIncrement,
                                              out bool lpTimeAdjustmentDisabled);
   
   public static void Main()
   {
      long timeAdjustment, timeIncrement = 0;
      bool timeAdjustmentDisabled;
      
      if (GetSystemTimeAdjustment(out timeAdjustment, out timeIncrement, 
                                  out timeAdjustmentDisabled)) {
         if (! timeAdjustmentDisabled)
            Console.WriteLine("System clock resolution: {0:N3} milliseconds", 
                              timeIncrement/10000.0);
         else
            Console.WriteLine("Unable to determine system clock resolution.");                     
      }
   }      
}
// The example displays output like the following:
//        System clock resolution: 15.600 milliseconds
Module Example
   Private Declare Function GetSystemTimeAdjustment Lib "Kernel32" (
                   ByRef lpTimeAdjustment As Long, ByRef lpTimeIncrement As Long,
                   ByRef lpTimeAdjustmentDisabled As Boolean) As Boolean

   Public Sub Main()
      Dim timeAdjustment, timeIncrement As Long
      Dim timeAdjustmentDisabled As Boolean
      
      If GetSystemTimeAdjustment(timeAdjustment, timeIncrement, 
                                  timeAdjustmentDisabled) Then
         If Not timeAdjustmentDisabled Then
            Console.WriteLine("System clock resolution: {0:N3} milliseconds", 
                              timeIncrement/10000.0)
         Else
            Console.WriteLine("Unable to determine system clock resolution.")                     
         End If
      End If
   End Sub
End Module
' The example displays output similar to the following:
'       System clock resolution: 15.625 milliseconds

Se seu aplicativo requer uma resolução maior do que o oferecido pelos Timer classe ou o relógio do sistema, use os timers de multimídia de alta resolução, consulte como: Usar o Timer de alta resolução.If your app requires greater resolution than that offered by the Timer class or the system clock, use the high-resolution multimedia timers; see How to: Use the High-Resolution Timer.

Se o intervalo é definido após o Timer tiver iniciado, a contagem é redefinida.If the interval is set after the Timer has started, the count is reset. Por exemplo, se você definir o intervalo de 5 segundos e, em seguida, defina as Enabled propriedade para true, a contagem começa no momento Enabled está definido.For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. Se você redefinir o intervalo de 10 segundos quando a contagem for 3 segundos, o Elapsed é gerado pela primeira vez e 13 segundos após Enabled foi definida como true.If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

Se Enabled é definido como true e AutoReset é definido como false, o Timer aciona o Elapsed eventos somente uma vez, na primeira vez que o intervalo tenha decorrido.If Enabled is set to true and AutoReset is set to false, the Timer raises the Elapsed event only once, the first time the interval elapses. Enabled em seguida, é definido como false.Enabled is then set to false.

Observação

Se Enabled e AutoReset são definidos como false, e o temporizador anteriormente tiver sido habilitado, definindo o Interval faz com que a propriedade a Elapsed evento seja acionado uma vez, como se o Enabled propriedade tivesse sido definida como true.If Enabled and AutoReset are both set to false, and the timer has previously been enabled, setting the Interval property causes the Elapsed event to be raised once, as if the Enabled property had been set to true. Para definir o intervalo sem acionar o evento, você pode definir temporariamente a Enabled propriedade para true, defina as Interval propriedade para o intervalo de tempo desejado e, em seguida, defina imediatamente o Enabled propriedade de volta para false.To set the interval without raising the event, you can temporarily set the Enabled property to true, set the Interval property to the desired time interval, and then immediately set the Enabled property back to false.

Aplica-se a

Veja também