在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#中實現定時功能的方法,您可以根據具體需求選擇適合的方法來實現定時任務。