System.Windows.Forms.Timer(UI 執行緒)或 System.Timers.Timer/System.Threading.Timer(背景執行緒)皆可實作定時任務。本文示範 WinForms Timer 每秒檢查是否到達指定時刻。
using System;
using System.Collections;
using System.Windows.Forms;
public class TimerDemo : Form
{
private Timer _timer;
private readonly ArrayList _schedule = new ArrayList
{ "08:30:00", "09:30:00", "10:30:00", "11:30:00" };
public TimerDemo()
{
_timer = new Timer { Interval = 1000 }; // 1 秒
_timer.Tick += Timer_Tick;
_timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
string now = DateTime.Now.ToLongTimeString(); // 格式 HH:mm:ss
foreach (string target in _schedule)
{
if (now == target)
{
MessageBox.Show($"現在時間是 {target},執行排程任務!");
// 實際應用:呼叫服務、寫入日誌、發送通知等
}
}
}
[STAThread]
static void Main() => Application.Run(new TimerDemo());
}
| 類別 | 命名空間 | 執行緒 | 適用場景 |
|---|---|---|---|
System.Windows.Forms.Timer | System.Windows.Forms | UI 執行緒 | WinForms 簡單 UI 更新、頻率低(≥ 50ms) |
System.Timers.Timer | System.Timers | ThreadPool | Server 端定時任務、需精確間隔、支援 AutoReset |
System.Threading.Timer | System.Threading | ThreadPool | 高效能、輕量、無 UI 相依、適合背景服務 |
// 使用 System.Threading.Timer 計算首次延遲
DateTime target = new DateTime(2024, 12, 31, 23, 59, 0);
TimeSpan due = target - DateTime.Now;
if (due < TimeSpan.Zero) due = TimeSpan.Zero;
var timer = new System.Threading.Timer(_ =>
{
Console.WriteLine("跨年倒數觸發!");
// 執行一次性任務
}, null, due, Timeout.InfiniteTimeSpan); // 不重複
Task.Run 併發處理。timer.Dispose() 或 timer.Change(Timeout.Infinite, ...)。Quartz.NET、Hangfire 或 FluentScheduler。