在C#中实现定时功能有多种方法,以下是其中几种常用的方法:
using System;
using System.Timers;
class Program
{
static void Main()
{
Timer timer = new Timer();
timer.Interval = 1000; // 设置定时器间隔为1秒
timer.Elapsed += Timer_Elapsed;
timer.Start();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Timer elapsed at: " + DateTime.Now.ToString("HH:mm:ss"));
}
}
using System;
using System.Threading;
class Program
{
static void Main()
{
TimerCallback callback = new TimerCallback(TimerCallbackMethod);
Timer timer = new Timer(callback, null, 0, 1000); // 延迟0秒后开始,每隔1秒执行一次
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
static void TimerCallbackMethod(object state)
{
Console.WriteLine("Timer elapsed at: " + DateTime.Now.ToString("HH:mm:ss"));
}
}
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
while (true)
{
Console.WriteLine("Timer elapsed at: " + DateTime.Now.ToString("HH:mm:ss"));
await Task.Delay(1000); // 延迟1秒后继续执行
}
}
}
以上是几种在C#中实现定时功能的方法,您可以根据具体需求选择适合的方法来实现定时任务。