Timer in C#

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started