Share via


Procedura: eseguire routine a intervalli predefiniti con il componente Timer Windows Form

A volte può essere necessario creare una routine che venga eseguita a intervalli di tempo specificati fino alla conclusione di un ciclo oppure al termine di un intervallo di tempo predefinito. Il componente Timer consente l'esecuzione di una routine di questo tipo.

Il componente è progettato per l'ambiente Windows Form. Per informazioni su un timer adatto a un ambiente server, vedere Introduzione ai timer basati su server.

Nota

L'utilizzo del componente Timer presenta alcune limitazioni. Per ulteriori informazioni, vedere Limitazioni della proprietà Interval del componente Timer di Windows Form.

Per eseguire una routine a intervalli predefiniti con il componente Timer

  1. Aggiungere una classe Timer al form. Vedere la sezione Esempio seguente per un'illustrazione sull'esecuzione di questa operazione a livello di codice. Visual Studio dispone anche di supporto per l'aggiunta di componenti a un form. Per ulteriori informazioni, vedere Procedura: aggiungere controlli senza interfaccia a un Windows Form e Procedura: aggiungere controlli senza interfaccia a un Windows Form e Procedura: aggiungere controlli senza interfaccia a un Windows Form e Procedura: aggiungere controlli senza interfaccia a un Windows Form.

  2. Impostare la proprietà Interval per il timer, in millisecondi. Questa proprietà determina il tempo che dovrà trascorrere prima che la routine venga eseguita nuovamente.

    Nota

    Quanto maggiore è la frequenza con cui si verifica un evento timer, tanto maggiore sarà il tempo di attività del processore richiesto per rispondere all'evento. In seguito a tale attività si potrebbe determinare una riduzione delle prestazioni generali. È pertanto opportuno non impostare un intervallo minore del necessario.

  3. Scrivere il codice appropriato nel gestore eventi per Tick. Il codice scritto in questo evento verrà eseguito con l'intervallo specificato nella proprietà Interval.

  4. Impostare la proprietà Enabled su true per avviare il timer. Si verificherà l'evento Tick e la routine verrà eseguita con l'intervallo impostato.

  5. Al momento appropriato, impostare la proprietà Enabled su false per impedire che la routine venga eseguita di nuovo. La semplice impostazione dell'intervallo su 0 non determinerà l'arresto del timer.

Esempio

Nel primo codice di esempio viene tenuta traccia dell'ora del giorno in incrementi di un secondo. Vengono utilizzati un componente Button, un componente Label e un componente Timer in un form. La proprietà Interval viene impostata su 1000, ovvero su un secondo. Nell'evento Tick, la didascalia dell'etichetta viene impostata sull'ora corrente. Quando si fa clic sul pulsante, la proprietà Enabled viene impostata su false, impedendo così l'aggiornamento della didascalia dell'etichetta da parte del timer. Per l'esempio di codice è necessario che si disponga di un form con un controllo Button denominato Button1, un controllo Timer denominato Timer1 e un controllo Label denominato 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;
      }
   }

Nel secondo esempio di codice viene eseguita una routine ogni 600 millisecondi, fino alla conclusione di un ciclo. Per l'esempio di codice è necessario che si disponga di un form con un controllo Button denominato Button1, un controllo Timer denominato Timer1 e un controllo Label denominato 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());
      }
   }

Vedere anche

Riferimenti

Cenni preliminari sul componente Timer (Windows Form)

Timer

Altre risorse

Componente Timer (Windows Form)