Timer in C#

CsharpProgrammingServer Side Programming

The namespace used to set a timer is System. Timers. The Timer class generates an event after a set interval, with an option to generate recurring events.

Firstly, create a timer object for 5 seconds interval −

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

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

timer.Elapsed += OnTimedEvent;

Now start the timer.

timer.Enabled = true;


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... ");

   private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
      Console.WriteLine("Raised: {0}", e.SignalTime);
Published on 14-Aug-2018 13:14:52