C# Timer: How to Use with Example
In C#, you can create and use a timer using the Timer class. Here is a simple example:
using System;
using System.Timers;
class Program
{
static Timer timer;
static void Main()
{
// 创建一个计时器,设置时间间隔为1000毫秒(1秒)
timer = new Timer(1000);
// 添加计时器触发事件的处理方法
timer.Elapsed += TimerElapsed;
// 启动计时器
timer.Start();
Console.WriteLine("计时器已启动。按任意键停止...");
Console.ReadKey();
// 停止计时器
timer.Stop();
Console.WriteLine("计时器已停止。");
}
static void TimerElapsed(object sender, ElapsedEventArgs e)
{
// 输出当前时间
Console.WriteLine($"当前时间:{DateTime.Now}");
}
}
In the examples above, a Timer class instance is created, and the time interval is set. The Elapsed event is then used to handle the timer-triggered event. In the Main method, the timer is first started and then awaits user input to stop the timer by pressing any key. When the timer triggers the Elapsed event, the TimerElapsed method is called to output the current time. Finally, the timer is stopped and a stop message is output.