Home  >  Article  >  Backend Development  >  Timer in C#

Timer in C#

PHPz
PHPzforward
2023-08-24 19:05:021514browse

Timer in C#

The namespace used to set timers is System.Timers. The Timer class generates an event after a set interval and optionally generates recurring events.

First, create a timer object with a 5-second interval −

timer = new System.Timers.Timer(5000);

Set the timer elapsed event. This event occurs when the interval elapses −

timer.Elapsed += OnTimedEvent;

Start timing now. The Chinese translation of

timer.Enabled = true;

Example

is:

Example

using System;
using System.Timers;

public class Demo {
   private static Timer timer;

   public static void Main() {
      timer = new System.Timers.Timer();
      timer.Interval = 5000;

      timer.Elapsed += OnTimedEvent;
      timer.AutoReset = true;
      timer.Enabled = true;

      Console.WriteLine("Press the Enter key to exit anytime... ");
      Console.ReadLine();
   }

   private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
      Console.WriteLine("Raised: {0}", e.SignalTime);
   }
}

The above is the detailed content of Timer in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete