Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Windows 服務開發入門:Visual Studio 建立 Timer 觸發資料庫備份/Remoting Host 服務,15 分鐘從零到部署

編輯:Windows XP 系統介紹

Windows 服務在背景無聲運作,適合定時備份、監控、Remoting 伺服器等長期運行任務。Visual Studio 提供「Windows Service」專案範本,拖曳 Timer 元件、撰寫幾行 ADO.NET 代碼、加入安裝程式、InstallUtil 註冊,即可完成專業級服務部署。

15 分鐘建立定時資料庫備份服務

  1. VS 新建專案 → 「Windows Service」 → 專案名 AutoBackupService。
  2. 設計介面 → 從「元件」工具箱拖入 Timer (非 Windows Forms Timer) → 設定 Interval = 200 (毫秒,每秒 5 次檢查)。
  3. 雙擊 Timer 進入 Tick 事件撰寫核心邏輯:
private void timer1_Tick(object sender, EventArgs e) {
    // 範例:每天 02:00 執行完整備份
    if (DateTime.Now.Hour == 2 && DateTime.Now.Minute == 0) {
        using (SqlConnection conn = new SqlConnection("Server=.;Database=MyDB;Trusted_Connection=True;")) {
            conn.Open();
            string cmdText = "BACKUP DATABASE MyDB TO DISK='D:\\Backup\\MyDB_' + FORMAT(GETDATE(),'yyyyMMdd') + '.bak'";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn)) {
                cmd.ExecuteNonQuery();
            }
        }
    }
}
  1. 切換設計檢視 → 右鍵「加入安裝程式」 → 產生 ProjectInstaller.cs。
  2. 設定 serviceInstaller1:ServiceName = "AutoBackupService"、StartType = Automatic。
  3. 設定 serviceProcessInstaller1:Account = LocalSystem (或 NetworkService/指定帳號)。
  4. 建置專案 (Release) → 輸出 AutoBackupService.exe。
  5. 管理員身分開啟 Visual Studio Developer Command Prompt → InstallUtil AutoBackupService.exe 註冊服務。
  6. services.msc → 找 "AutoBackupService" → 右鍵「啟動」→ 設為「自動」→ 完成部署。

進階主題

  • 服務復原: 服務屬性 → 「復原」索引標籤 → 失敗時「重新啟動服務」/「執行程式」/「重新啟動電腦」。
  • 事件日誌: 使用 EventLog.WriteEntry 記錄關鍵操作,方便事後稽核。
  • .NET Core / .NET 5+ Worker Service: 新專案範本 Worker Service,支援跨平台、依賴注入、IHostedService 模式,部署為 systemd/Linux 服務或 Windows 服務皆可。

避坑指南:Timer Interval 不要設太短 (≤100ms) 避免 CPU 佔用過高;資料庫連線字串請放入 app.config 加密區段,勿硬編碼;服務帳號遵循最小權限原則,勿濫用 LocalSystem。

Copyright © Windows教程網 All Rights Reserved