Compartilhar via


Como: Executar procedimentos em intervalos de conjunto com o componente Timer do Windows Forms

Às vezes, convém criar um procedimento que é executado em intervalos de time específico até um loop foi concluída ou que seja executado quando um conjunto intervalo de time decorrido.The Timer componente permite que tal um procedimento.

Este componente é projetado para um ambiente Windows Forms.Se você precisar de um temporizador que é adequado para um ambiente de servidor, consulte Introdução a timers com base no servidor.

Observação:

Existem algumas limitações ao usar o Timer componente. Para obter mais informações, consulte Limitações Interval propriedade do componente Windows Forms Timer.

Para executar um procedimento em conjunto intervalos com o componente Timer

  1. Adicionar um Timer ao seu formulário. Consulte a seção exemplo a seguir para obter uma ilustração de como fazer isso programaticamente.Visual Studio também tem suporte para adicionar componentes a um formulário.

  2. conjunto o Interval propriedade (em milissegundos) para o timer. Esta propriedade determina quanto time passará antes que o procedimento seja executado novamente.

    Observação:

    Mais freqüentemente um evento timer ocorre, mais time do processador é usado em responder ao evento.Isso pode tornar lento o desempenho geral.Não conjunto um intervalo menor do que o necessário.

  3. gravar apropriado de código no Tick manipulador de eventos. O código que você escreve nesse evento será executado no intervalo especificado no Interval propriedade.

  4. conjunto o Enabled propriedade para true Para iniciar o cronômetro. The Tick evento irá começar a ocorrer, executando o procedimento na conjunto intervalo.

  5. No momento adequado, conjunto o Enabled propriedade para false Para interromper o procedimento seja executado novamente. Definir o intervalo para 0 não pode fazer com que o timer de parar.

Exemplo

Neste primeiro exemplo de código registra a time do dia em incrementos de um segundo.Ele usa um Button, um Labele um Timer componente em um formulário. The Interval propriedade é conjunto a 1000 (igual a um segundo). No Tick legenda do rótulo de evento, é conjunto para a time corrente. Quando o botão for clicado, a Enabled propriedade estiver definida como false, interrompendo o cronômetro da legenda do rótulo de atualização. O exemplo de código a seguir requer que você tenha um formulário com um Button controle de chamada Button1, um Timer controle de chamada Timer1e um Label controle de chamada 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()
{
   //' Run this procedure in an appropriate event.
   // Set to 1 second.
   Timer1.Interval = 1000;
   // Enable timer.
   Timer1.Enabled = true;
   Button1.Text = "Stop";
}

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

private void Button1_Click()
{
  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.set_Interval(1000);
   // Enable timer.
   Timer1.set_Enabled(true);
   Button1.set_Text("Stop");
}

private void Timer1_Tick(System.Object Sender, EventArgs e) 
{
   // Set the caption to the current time.
   Label1.set_Text(DateTime.get_Now().ToString());
}

private void Button1_Click() 
{
   if ( Button1.get_Text() == "Stop"  ) 
   {
      Button1.set_Text("Start");
      Timer1.set_Enabled(false);
   }
   else
   {
      Button1.set_Text("Stop");
      Timer1.set_Enabled(true);
   }
}
private:
   void InitializeTimer()
   {
      // Run this procedure in an appropriate event.
      // Set to 1 second.
      timer1->Interval = 1000;
      // Enable timer.
      timer1->Enabled = true;
      button1->Text = S"Stop";
   }

   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;
      }
   }

Este segundo exemplo de código executa um procedimento cada 600 milissegundos até que tenha terminado a um loop.O exemplo de código a seguir requer que você tenha um formulário com um Button controle de chamada Button1, um Timer controle de chamada Timer1e um Label controle de chamada 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());
      }
   }

Consulte também

Referência

Timer componente visão geral (Windows Forms)

Timer

Outros recursos

Timer componente (Windows Forms)