Compartir a través de


Cómo: Ejecutar procedimientos a intervalos establecidos con el componente Timer de formularios Windows Forms

A veces necesitará crear un procedimiento que se ejecute a intervalos específicos de tiempo hasta que finaliza un bucle o que se ejecute una vez transcurrido un intervalo de tiempo establecido. El componente Timer hace posible este procedimiento.

Este componente está diseñado para un entorno de formularios Windows Forms. Si necesita un temporizador que sea adecuado para un entorno de servidor, vea Introduction to Server-Based Timers.

Nota

Hay algunas limitaciones al utilizar el componente Timer. Para obtener más información, vea Limitaciones de la propiedad Interval del componente Timer de formularios Windows Forms.

Para ejecutar un procedimiento a intervalos establecidos con el componente Timer

  1. Agregue un Timer al formulario. Vaya a la siguiente sección Ejemplo para ver cómo hacerlo mediante programación. Visual Studio también admite agregar componentes a un formulario. Para obtener más información, vea Cómo: Agregar controles sin una interfaz de usuario a formularios Windows Forms y Cómo: Agregar controles sin una interfaz de usuario a formularios Windows Forms y Cómo: Agregar controles sin una interfaz de usuario a formularios Windows Forms y Cómo: Agregar controles sin una interfaz de usuario a formularios Windows Forms.

  2. Establezca la propiedad Interval (en milisegundos) para el temporizador. Esta propiedad determina cuánto tiempo transcurrirá antes de que el procedimiento se ejecute de nuevo.

    Nota

    Cuanto mayor sea la frecuencia con que se produce el evento del temporizador, más tiempo del procesador se utilizará para responder al evento. Esto puede ralentizar el rendimiento general. No establezca un intervalo menor que el necesario.

  3. Escriba el código adecuado en el controlador del evento Tick. El código que escriba en este evento se ejecutará según el intervalo especificado en la propiedad Interval.

  4. Establezca la propiedad Enabled en true para iniciar el temporizador. Comenzará a producirse el evento Tick, que ejecuta el procedimiento según el intervalo establecido.

  5. En el momento adecuado, establezca la propiedad Enabled en false para impedir que el procedimiento se ejecute de nuevo. Establecer el intervalo en 0 no hace que se detenga el temporizador.

Ejemplo

Este ejemplo de código efectúa un seguimiento de la hora del día con incrementos de un segundo. Utiliza una clase Button, una Label y un componente Timer de un formulario. La propiedad Interval se establece como 1.000 (igual a un segundo). En el evento Tick, la leyenda de la etiqueta se establece como la hora actual. Al hacer clic en el botón, la propiedad Enabled se establece en false, lo que hace que el temporizador deje de actualizar la leyenda de la etiqueta. El ejemplo de código siguiente requiere que tenga un formulario con un control Button denominado Button1, un control Timer denominado Timer1 y un control Label denominado Label1.

Private Sub InitializeTimer()
   ' Run this procedure in an appropriate event.
   ' Set to 1 second.
   Timer1.Interval = 1000
   ' Enable timer.
   Timer1.Enabled = True
   Button1.Text = "Enabled"
End Sub
x
Private Sub Timer1_Tick(ByVal Sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
' Set the caption to the current time.
   Label1.Text = DateTime.Now
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      If Button1.Text = "Stop" Then
         Button1.Text = "Start"
         Timer1.Enabled = False
      Else
         Button1.Text = "Stop"
         Timer1.Enabled = True
      End If
End Sub
private void InitializeTimer()
{
    // Call this procedure when the application starts.
    // Set to 1 second.
    Timer1.Interval = 1000;
    Timer1.Tick += new EventHandler(Timer1_Tick);

    // Enable timer.
    Timer1.Enabled = true;

    Button1.Text = "Stop";
    Button1.Click += new EventHandler(Button1_Click);
}

private void Timer1_Tick(object Sender, EventArgs e)   
{
   // Set the caption to the current time.
   Label1.Text = DateTime.Now.ToString();
}

private void Button1_Click(object sender, EventArgs e)
{
  if ( Button1.Text == "Stop" )
  {
    Button1.Text = "Start";
    Timer1.Enabled = false;
  }
  else
  {
    Button1.Text = "Stop";
    Timer1.Enabled = true;
  }
}
private:
   void InitializeTimer()
   {
      // Run this procedure in an appropriate event.
      // Set to 1 second.
      timer1->Interval = 1000;
      // Enable timer.
      timer1->Enabled = true;
      this->timer1->Tick += gcnew System::EventHandler(this,  
                               &Form1::timer1_Tick);

      button1->Text = S"Stop";
      this->button1->Click += gcnew System::EventHandler(this, 
                               &Form1::button1_Click);
   }

   void timer1_Tick(System::Object ^ sender,
      System::EventArgs ^ e)
   {
      // Set the caption to the current time.
      label1->Text = DateTime::Now.ToString();
   }

   void button1_Click(System::Object ^ sender,
      System::EventArgs ^ e)
   {
      if ( button1->Text == "Stop" )
      {
         button1->Text = "Start";
         timer1->Enabled = false;
      }
      else
      {
         button1->Text = "Stop";
         timer1->Enabled = true;
      }
   }

En este segundo ejemplo se ejecuta un procedimiento cada 600 milisegundos hasta que termina un bucle. El ejemplo de código siguiente requiere que tenga un formulario con un control Button denominado Button1, un control Timer denominado Timer1 y un control Label denominado Label1.

' This variable will be the loop counter.
Private counter As Integer

Private Sub InitializeTimer()
   ' Run this procedure in an appropriate event.
   counter = 0
   Timer1.Interval = 600
   Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
   If counter => 10 Then
      ' Exit loop code.
      Timer1.Enabled = False
      counter = 0
   Else
      ' Run your procedure here.
      ' Increment counter.
      counter = counter + 1
      Label1.Text = "Procedures Run: " & counter.ToString
   End If
End Sub
// This variable will be the loop counter.
private int counter;

private void InitializeTimer()
{
   // Run this procedure in an appropriate event.
   counter = 0;
   timer1.Interval = 600;
   timer1.Enabled = true;
   // Hook up timer's tick event handler.
   this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}

private void timer1_Tick(object sender, System.EventArgs e)   
{
   if (counter >= 10) 
   {
      // Exit loop code.
      timer1.Enabled = false;
      counter = 0;
   }
   else
   {
      // Run your procedure here.
      // Increment counter.
      counter = counter + 1;
      label1.Text = "Procedures Run: " + counter.ToString();
      }
}
// Run this procedure in an appropriate event.
counter = 0;
timer1.set_Interval(600);
timer1.set_Enabled(true);
// Wire up timer's tick event handler.
this.timer1.add_Tick(new System.EventHandler(this.timer1_Tick));

private void timer1_Tick(System.Object sender, System.EventArgs e) 
{
   if ( counter >= 10  ) 
   {
      // Exit loop code.
      timer1.set_Enabled(false);
      counter = 0;
   }
   else
   {
      // Run your procedure here.
      // Increment counter.
      counter = counter + 1;
      this.timer1.add_Tick(new System.EventHandler(this.timer1_Tick));
   }
}
private:
   int counter;

   void InitializeTimer()
   {
      // Run this procedure in an appropriate event.
      counter = 0;
      timer1->Interval = 600;
      timer1->Enabled = true;
      // Hook up timer's tick event handler.
      this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);
   }

   void timer1_Tick(System::Object ^ sender,
      System::EventArgs ^ e)
   {
      if (counter >= 10) 
      {
         // Exit loop code.
         timer1->Enabled = false;
         counter = 0;
      }
      else
      {
         // Run your procedure here.
         // Increment counter.
         counter = counter + 1;
         label1->Text = String::Concat("Procedures Run: ",
            counter.ToString());
      }
   }

Vea también

Referencia

Información general sobre el componente Timer (formularios Windows Forms)

Timer

Otros recursos

Timer (Componente, formularios Windows Forms)