傳統方案:Windows Service、SQL Agent、Windows Task Scheduler、第三方排程器 (Quartz.NET, Hangfire)。但在以下情境,內建排程極具優勢:
// 任務介面
public interface IScheduledJob
{
void Execute();
}
// 具體任務:定時寫入時間記錄
public class LogTimeJob : IScheduledJob
{
public void Execute()
{
string logPath = HttpContext.Current?.Server.MapPath("~/App_Data/ScheduleLog.txt")
?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "ScheduleLog.txt");
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string logEntry = $"{timestamp} - 排程任務執行{Environment.NewLine}";
File.AppendAllText(logPath, logEntry);
}
}
// 排程配置
public class SchedulerConfiguration
{
public int IntervalMilliseconds { get; }
public List Jobs { get; } = new List();
public SchedulerConfiguration(int intervalSeconds)
{
IntervalMilliseconds = intervalSeconds * 1000;
}
}
// 排程引擎
public class Scheduler
{
private readonly SchedulerConfiguration _config;
private readonly CancellationTokenSource _cts = new();
private Task _workerTask;
public Scheduler(SchedulerConfiguration config) => _config = config;
public void Start()
{
_workerTask = Task.Run(async () =>
{
while (!_cts.Token.IsCancellationRequested)
{
foreach (var job in _config.Jobs)
{
if (_cts.Token.IsCancellationRequested) break;
try
{
job.Execute();
}
catch (Exception ex)
{
// 記錄錯誤但不中斷其他任務
System.Diagnostics.Debug.WriteLine($"排程任務錯誤: {ex}");
}
}
try { await Task.Delay(_config.IntervalMilliseconds, _cts.Token); }
catch (OperationCanceledException) { break; }
}
}, _cts.Token);
}
public void Stop()
{
_cts.Cancel();
_workerTask?.Wait(TimeSpan.FromSeconds(5));
}
}
public class Global : HttpApplication
{
private static Scheduler _scheduler;
protected void Application_Start(object sender, EventArgs e)
{
// 1. 建立配置:每 30 秒執行一次
var config = new SchedulerConfiguration(30);
config.Jobs.Add(new LogTimeJob());
// config.Jobs.Add(new CleanupTempFilesJob());
// config.Jobs.Add(new SyncDataJob());
// 2. 啟動排程器
_scheduler = new Scheduler(config);
_scheduler.Start();
}
protected void Application_End(object sender, EventArgs e)
{
// 3. 優雅關閉
_scheduler?.Stop();
}
}
protected void Application_End(object sender, EventArgs e)
{
// 應用程式結束前,發送請求喚醒自己 (需謹慎使用)
Task.Run(async () =>
{
await Task.Delay(15000); // 等待關閉完成
try
{
string url = $"https://{HttpContext.Current?.Request.Url.Host}/warmup?tick={DateTime.Now.Ticks}";
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) })
{
await client.GetAsync(url);
}
}
catch { /* 忽略 */ }
});
}
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="false">
<add initializationPage="/warmup" />
</applicationInitialization>
</system.webServer>
當任務變複雜 (重試、排程表達式、儀表板、分散式鎖、失敗通知),請遷移成熟框架:
// Startup.cs
services.AddHangfire(c => c.UseSqlServerStorage(connectionString));
services.AddHangfireServer();
// 定義任務
RecurringJob.AddOrUpdate(() => Console.WriteLine("每分鐘執行"), Cron.Minutely);
RecurringJob.AddOrUpdate(s => s.SendDailyReport(), Cron.Daily(8, 0));
// 延遲執行
BackgroundJob.Schedule(() => SendWelcomeEmail(userId), TimeSpan.FromHours(1));
// 定義 Job
public class EmailJob : IJob
{
public Task Execute(IJobExecutionContext context) { ... }
}
// 配置排程
var job = JobBuilder.Create().Build();
var trigger = TriggerBuilder.Create()
.WithCronSchedule("0 0 8 * * ?") // 每天 08:00
.Build();
scheduler.ScheduleJob(job, trigger);
| 方案 | 複雜度 | 持久化 | 分散式 | 監控/重試 | 適用場景 |
|---|---|---|---|---|---|
| 內建 Timer/Task | 低 | 無 (記憶體) | 不支援 | 無 | 極簡需求、共享主機、原型 |
| Windows Service | 中 | 可自行實作 | 需額外協調 | 自行實作 | 獨立伺服器、長期運行 |
| SQL Agent | 中 | 資料庫 | 單點 | 基本 | 資料庫維護、ETL |
| Hangfire | 低 | 資料庫 (SQL/Redis) | 支援 | 完整 (儀表板、重試、刪除) | 大多數 Web 應用首選 |
| Quartz.NET | 中高 | 資料庫/RAM | 支援 (叢集) | 豐富 (Calendar、Misfire 處理) | 企業級複雜排程需求 |
| Azure Functions / AWS Lambda | 低 (程式碼) | 平台管理 | 原生支援 | 平台內建 | 雲端原生、事件驅動、按量付費 |
ASP.NET 內建排程任務透過 `Application_Start` 啟動背景 `Task` 實現極簡部署,適合輕量需求。但**必須面對 IIS 回收機制導致的不可靠性**,需結合 IIS 設定調整、外部監控喚醒、應用程式初始化模組等手段緩解。一旦業務邏輯涉及重試、失敗通知、排程表達式、分散式部署,請果斷遷移至 **Hangfire** 或 **Quartz.NET** 等成熟框架,專注於業務邏輯而非基礎建設維護。