Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

How to use Timer in C#

Hassan Azhar

5289679973777408## Timer The System.Timer class in C# offers a way to run a block of code after a set interval of time – it can be run repeatedly.

This sort of module has various applications and is ideal for use in web applications to check the status of a connection. Another application might be a timer for a video game.

svg viewer

Implementation

The following example demonstrates how the System.Timer class is used.

using System;
using System.Timers;

class TimerExample
{
  private static System.Timers.Timer timer;

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

      // Setting up Timer
      timer.Interval = 5000;
      timer.Elapsed += OnTimedEvent;
      timer.AutoReset = true;
      timer.Enabled = true;

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

      // Releasing Timer resources once done
      timer.Stop();
      timer.Dispose();
  }

  private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) {
      // Code to be executed at the end of Timer 
      Console.WriteLine("Timer ending 5 second count");
  }
}

To run this program, press RUN. Then, type csc main.cs in the terminal to compile it. To run the resultant code, type mono main.exe into the terminal and press enter. To make any changes to the program, repeat the process from the start.

The timer variable is declared inside the class-scope to make it accessible in all functions.

This may not be necessary here, but it is a good practice.

The Interval property sets the time interval, in milliseconds, after which the required code is to be run.

The Elapsed property sets the function that will be executed upon the end of the time interval.

This function has to have parameters of the Object and System.Timers.ElapsedEventArgs type. In this case, this function is OnTimedEvent. AutoReset sets the timer to reset and starts counting from zero once the interval has ended. If this is set to false, the timer has to be reset by a call to the Start() function – the Enabled property will start the countdown. Once the program is done with the timer, it should be stopped and its resources released for use elsewhere.

The timer is stopped by the Stop() function, and the Dispose() function makes its resources available.

RELATED TAGS

c#

CONTRIBUTOR

Hassan Azhar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring