首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows Service 定時任務實作:System.Timers.Timer 排程寫入日誌完整範例

     編輯:關於.NET

建立 Windows 服務專案,使用 `System.Timers.Timer` 實現定時排程 (每 9 秒寫入文字檔與事件日誌),含安裝部署、屬性設定、原始碼下載。

專案建立步驟

  1. VS → 新增專案 → **Windows 服務** → `WindowsServiceDemo`
  2. 設計介面:從工具箱拖入 **Timer** (注意:`System.Timers.Timer`,非 `Windows.Forms.Timer`)
  3. 右鍵設計介面 → **加入安裝程式** → 產生 `ProjectInstaller.cs`

設計介面與 Timer 元件

安裝程式屬性

服務核心代碼

public partial class Service1 : ServiceBase
{
    private string _flag = "開始時間:";
    private bool _isRunning = false; // 防止重入

    public Service1()
    {
        InitializeComponent();
        timer1.Interval = 9000; // 9 秒
        timer1.Elapsed += Timer1_Elapsed;
    }

    protected override void OnStart(string[] args)
    {
        _flag = "開始時間:";
        timer1.Enabled = true;
        WriteLog("服務已啟動");
    }

    protected override void OnStop()
    {
        timer1.Enabled = false;
        WriteLog("服務已停止");
    }

    private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (_isRunning) return; // 防止重入
        _isRunning = true;
        try
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Welcome.txt");
            using (var fs = new FileStream(path, FileMode.Append, FileAccess.Write))
            using (var sw = new StreamWriter(fs))
            {
                sw.WriteLine(_flag + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sw.WriteLine("Welcome to Write:" + DateTime.Now.ToFileTimeUtc());
                sw.WriteLine();
            }
            WriteLog("已寫入歡迎訊息");
        }
        catch (Exception ex)
        {
            WriteLog($"錯誤: {ex.Message}", EventLogEntryType.Error);
        }
        finally
        {
            _isRunning = false;
        }
    }

    private void WriteLog(string message, EventLogEntryType type = EventLogEntryType.Information)
    {
        if (!EventLog.SourceExists("WindowsServiceDemo"))
            EventLog.CreateEventSource("WindowsServiceDemo", "Application");
        EventLog.WriteEntry("WindowsServiceDemo", message, type);
    }
}

安裝與啟動

  1. 開啟 **Developer Command Prompt for VS** (管理員)
  2. 進入專案 `bin\Debug` 目錄
  3. 執行 `installutil WindowsServiceDemo.exe`
  4. 開啟 `services.msc` → 找到 `WindowsServiceDemo` → **啟動**

服務管理器

驗證結果

  • 檔案 `Welcome.txt` 每 9 秒新增一行
  • 事件檢視器 `eventvwr.msc` → Windows Logs → Application → 來源 `WindowsServiceDemo` 可見資訊/錯誤日誌

    事件檢視器

安裝程式屬性說明

屬性值說明
ServiceInstaller.StartTypeAutomatic開機自動啟動
ServiceInstaller.StartTypeManual需手動啟動
ServiceInstaller.StartTypeDisabled無法啟動
ServiceProcessInstaller.AccountLocalSystem高權限,本機系統帳戶
ServiceProcessInstaller.AccountNetworkService網路服務帳戶,有網路權限
ServiceProcessInstaller.AccountUser指定使用者帳戶 (安裝時輸入)

適用場景與擴充建議

  • 定時資料同步、報表產生、郵件發送、清理暫存檔
  • 長時間任務:改用 `Task.Run` + `CancellationToken` 避免阻塞 Timer 執行緒
  • 叢集環境:引入分散式鎖 (Redis/DB) 確保單節點執行
  • 現代替代方案:.NET 6+ `BackgroundService` + `IHostedService` (主控台/Worker Service 專案),跨平台、DI 整合、優雅關閉

Windows Service 是傳統 .NET Framework 長期運行背景任務的標準載體。核心在於 `OnStart/OnStop` 生命週期、`Timer` 排程、防重入、`EventLog` 可觀測性。

資源下載

  • 原始碼:WindowsServiceDemo.rar
  • PDF 文件:`Windows服務程序時鐘調用.pdf`、`Windows服務創建文檔.pdf`
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved