前言
程序猿小張最近遇到了一個(gè)難題——他需要每天早上9點(diǎn)自動(dòng)給老板發(fā)送工作報(bào)告,就像個(gè)數(shù)字化的公雞打鳴一樣準(zhǔn)時(shí)。在C#的世界里,這樣的定時(shí)任務(wù)該怎么實(shí)現(xiàn)呢?
定時(shí)器在編程中就像你的私人助理,可以幫你按時(shí)執(zhí)行各種任務(wù):數(shù)據(jù)備份、郵件發(fā)送、緩存清理...
今天,就讓我們一起來探索C#中那些讓你成為 "時(shí)間管理大師" 的定時(shí)器吧!
1. System.Timers.Timer
System.Timers.Timer
就像一個(gè)全能型選手,它是基于服務(wù)器的定時(shí)器,精度較高,適合需要在特定時(shí)間間隔重復(fù)執(zhí)行的任務(wù),特別要說明的是,它是線程安全的。
using System;
using System.Timers;
classProgram
{
static void Main()
{
var timer = new System.Timers.Timer(1000); // 1秒間隔
timer.Elapsed += (sender, e) =>
{
Console.WriteLine($"定時(shí)任務(wù)執(zhí)行啦!時(shí)間:{e.SignalTime}");
};
timer.AutoReset = true; // 設(shè)置為重復(fù)觸發(fā)
timer.Start();
Console.WriteLine("按任意鍵退出...");
Console.ReadKey();
timer.Stop();
}
}
2. System.Threading.Timer
System.Threading.Timer
是一個(gè)輕量級(jí)的定時(shí)器,它性能更好,沒有UI組件依賴,適合后臺(tái)任務(wù),不過在使用時(shí),一定要記得手動(dòng)釋放資源。
using System;
using System.Threading;
classProgram
{
static void Main()
{
// 參數(shù):回調(diào)方法, 狀態(tài)對(duì)象, 延遲時(shí)間, 間隔時(shí)間
var timer = new Timer(state =>
{
Console.WriteLine($"線程定時(shí)器觸發(fā)!時(shí)間:{DateTime.Now}");
}, null, 1000, 2000); // 1秒后開始,每2秒觸發(fā)
Console.WriteLine("按任意鍵退出...");
Console.ReadKey();
timer.Dispose(); // 記得釋放資源
}
}
3. System.Windows.Forms.Timer
這是一個(gè)專為 Windows Forms 設(shè)計(jì)的定時(shí)器,事件在 UI 線程上觸發(fā),可以直接操作 UI 控件,非常適合用于更新用戶界面元素,不過,它的精度較低(約55ms),不太適合高精度定時(shí)。
using System;
using System.Windows.Forms;
classProgram
{
static void Main()
{
var form = new Form();
var timer = new Timer { Interval = 1000 }; // 1秒間隔
timer.Tick += (sender, e) =>
{
Console.WriteLine($"窗體定時(shí)器觸發(fā)!時(shí)間:{DateTime.Now}");
};
timer.Start();
Application.Run(form);
}
}
4. Stopwatch
Stopwatch
通常用來測(cè)量程序的執(zhí)行時(shí)間,它的精度非常高,達(dá)到微秒級(jí),所以換一個(gè)思路,也可以把它作為定時(shí)器,比如下面這個(gè)例子:
using System;
using System.Diagnostics;
using System.Threading;
classProgram
{
static void Main()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
if (stopwatch.ElapsedMilliseconds >= 1000)
{
Console.WriteLine($"高精度計(jì)時(shí)!時(shí)間:{DateTime.Now}");
stopwatch.Restart();
}
Thread.Sleep(10); // 降低CPU占用
}
}
}
5. Thread.Sleep 和 Task.Delay
有時(shí)候,我們只需要簡(jiǎn)單的延遲執(zhí)行某些代碼,這時(shí)候可以使用 Thread.Sleep(同步)或 Task.Delay(異步) 來實(shí)現(xiàn),如:
using System;
using System.Threading.Tasks;
public class AsyncAwaitExample
{
public static async Task Main(string[] args)
{
Console.WriteLine("開始計(jì)時(shí)...");
await Task.Delay(5000); // 等待5秒
Console.WriteLine("5秒后...");
}
}
總結(jié)
現(xiàn)在你已經(jīng)掌握了 C# 定時(shí)器的“十八般武藝”,是時(shí)候做個(gè)總結(jié)了!
- 簡(jiǎn)單任務(wù):System.Threading.Timer/Task.Delay(Thread.Sleep)
- 簡(jiǎn)單任務(wù)且高精度:Stopwatch
- UI相關(guān):Windows.Forms.Timer
- 服務(wù)器應(yīng)用:System.Timers.Timer
現(xiàn)在,去用代碼馴服時(shí)間吧!
該文章在 2025/6/2 12:49:18 編輯過