In C#, a timer is a component that allows you to execute a code block on a regular interval. It can be useful for running background tasks, updating user interfaces, and more. In this post, we’ll go through the syntax for a timer in C# and show you how to utilize it in a piece of code.
timer in C#
In C#, a timer is a class that allows you to execute code at regular intervals. It is part of the System.Timers namespace and provides a way to schedule code to run after a certain amount of time has elapsed, the syntax for a timer in C# is as follows:
Let’s break down the different parts of the timer syntax in C#:
First, a new timer object is created through the Timer class using the below code line:
Next, the interval is set at which the timer should execute the code block, here the timer is set to execute the code block every 1000 milliseconds, or 1 second:
Now enable the timer so that it can start executing the code block using the following code line:
If you add an event handler to the timer’s elapsed event, it will be called each time the timer period expires.
Define the code block that should be executed when the timer interval elapses. In this example, we’ve defined a method called Timer_Elapsed that takes in a sender object and an ElapsedEventArgs object. Every time the timer interval expires, the code contained in this function will be carried out.
{
// Code block to execute on timer interval
}
Let’s put this timer syntax into practice with an example C# program. In this example, we will use a timer to print the current time to the console every 5 seconds.
using System.Timers;
class Program
{
static void Main(string[] args)
{
Timer timer = new Timer();
timer.Interval = 6000;
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
Console.WriteLine("Timer started. To exit press any key.");
Console.ReadKey();
}
static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Time now is : {0}", DateTime.Now);
}
}
In this example, we have created a timer object and set its interval to 5 seconds. The timer has also been turned on, and an event handler has been added to the Elapsed event. This event handler simply prints the current time to the console.
In the Main method, we have added a console message to indicate that the timer has started. We have also included a Console.ReadKey() statement to refrain the code from exiting immediately. This way, we can see the output from the timer before the program ends.
Conclusion
A timer in C# is a useful component that can be used to execute a code block on a regular interval. The syntax for a timer in C# involves creating a timer object, setting its interval, and enabling it. After that attach an event handler to the Elapsed event and define the code block to be executed when the timer interval elapses.