Dot-Net
Windows 服務中定時器的使用
我有一個 Windows 服務,我想每 10 秒創建一個文件。
我收到很多評論,Windows 服務中的 Timer 將是最佳選擇。
我怎樣才能做到這一點?
首先,選擇正確的計時器。您想要
System.Timers.Timer或System.Threading.Timer- 不要使用與 UI 框架關聯的一個(例如System.Windows.Forms.Timer或DispatcherTimer)。定時器通常很簡單
- 設置刻度間隔
- 向
Elapsed事件添加處理程序(或在構造時將回調傳遞給它),- 必要時啟動計時器(不同的類工作方式不同)
一切都會好起來的。
樣品:
// System.Threading.Timer sample using System; using System.Threading; class Test { static void Main() { TimerCallback callback = PerformTimerOperation; Timer timer = new Timer(callback); timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1)); // Let the timer run for 10 seconds before the main // thread exits and the process terminates Thread.Sleep(10000); } static void PerformTimerOperation(object state) { Console.WriteLine("Timer ticked..."); } } // System.Timers.Timer example using System; using System.Threading; using System.Timers; // Disambiguate the meaning of "Timer" using Timer = System.Timers.Timer; class Test { static void Main() { Timer timer = new Timer(); timer.Elapsed += PerformTimerOperation; timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds; timer.Start(); // Let the timer run for 10 seconds before the main // thread exits and the process terminates Thread.Sleep(10000); } static void PerformTimerOperation(object sender, ElapsedEventArgs e) { Console.WriteLine("Timer ticked..."); } }我在此頁面上有更多資訊,儘管我已經很長時間沒有更新了。