Поделиться через


Выполнение операций с заданной периодичностью с помощью компонента Timer в Windows Forms

Обновлен: Ноябрь 2007

Иногда бывает необходимо создать процедуру, которая выполняется через определенные интервалы времени до окончания цикла или запускается по истечении установленного интервала. Создание такой процедуры возможно благодаря компоненту Timer.

Этот компонент предназначен для среды Windows Forms. Если требуется таймер для серверной среды, см. раздел Знакомство с серверными таймерами.

3tszykws.alert_note(ru-ru,VS.90).gifПримечание.

При использовании компонента Timer необходимо учитывать ряд ограничений. Дополнительные сведения см. в разделе Ограничения свойства Interval компонента Timer в Windows Forms.

Чтобы выполнять процедуру через заданные интервалы времени с помощью компонента Timer, выполните следующие действия:

  1. Добавьте элемент управления Timer в форму. В приведенном ниже примере показано, как сделать это программным путем. Visual Studio также поддерживает добавление компонентов в форму. Дополнительные сведения см. в разделах Практическое руководство. Добавление элементов управления, для которых не существует пользовательского интерфейса, в формы Windows Forms и Практическое руководство. Добавление элементов управления, для которых не существует пользовательского интерфейса, в формы Windows Forms.

  2. Задайте значение свойства Interval (в миллисекундах) для таймера. Это свойство определяет, сколько времени пройдет до момента повторного выполнения процедуры.

    3tszykws.alert_note(ru-ru,VS.90).gifПримечание.

    Чем чаще происходит событие срабатывания таймера, тем больше времени процессора используется для отклика на событие. Это может снизить общую производительность. Не устанавливайте значение интервала ниже необходимой частоты.

  3. Напишите соответствующий код в обработчике событий Tick. Код этого обработчика будет выполняться с интервалом, указанным в свойстве Interval.

  4. Чтобы запустить таймер, установите для свойства Enabled значение true. Начнется генерация события Tick, запускающего процедуру с заданным интервалом.

  5. Чтобы отменить повторный запуск процедуры, в нужный момент присвойте свойству Enabled значение false. Задание интервала 0 не приведет к остановке таймера.

Пример

В первом примере кода отслеживается время дня с интервалами, равными одной секунде. Используется форма с элементами управления Button, Label и компонентом Timer. Свойству Interval присваивается значение 1000 (эквивалентно одной секунде). В событии Tick в заголовке метки устанавливается текущее время. При нажатии кнопки свойству Enabled присваивается значение false, после чего таймер перестает обновлять заголовок метки. В следующем примере кода требуется наличие формы с элементом управления Button с именем Button1, элементом управления Timer с именем Timer1 и элементом управления Label с именем 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;
      }
   }

Во втором примере кода процедура выполняется каждые 600 миллисекунд до тех пор, пока цикл не будет завершен. В следующем примере кода требуется наличие формы с элементом управления Button с именем Button1, элементом управления Timer с именем Timer1 и элементом управления Label с именем 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());
      }
   }

См. также

Ссылки

Общие сведения о компоненте Timer (Windows Forms)

Timer

Другие ресурсы

Компонент Timer (Windows Forms)