Timer 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
在設定間隔後產生事件,並可選擇產生重複事件。
public ref class Timer : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public class Timer : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type Timer = class
inherit Component
interface ISupportInitialize
Public Class Timer
Inherits Component
Implements ISupportInitialize
- 繼承
- 實作
範例
以下範例實例化一個 System.Timers.Timer 物件,每兩秒(2,000毫秒)觸發事件 Timer.Elapsed ,為該事件設定事件處理程序,並啟動計時器。 事件處理程序每次屬性被提出時都會顯示該屬性的 ElapsedEventArgs.SignalTime 值。
using System;
using System.Timers;
public class Example
{
private static System.Timers.Timer aTimer;
public static void Main()
{
SetTimer();
Console.WriteLine("\nPress the Enter key to exit the application...\n");
Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
Console.ReadLine();
aTimer.Stop();
aTimer.Dispose();
Console.WriteLine("Terminating the application...");
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
}
// The example displays output like the following:
// Press the Enter key to exit the application...
//
// The application started at 09:40:29.068
// The Elapsed event was raised at 09:40:31.084
// The Elapsed event was raised at 09:40:33.100
// The Elapsed event was raised at 09:40:35.100
// The Elapsed event was raised at 09:40:37.116
// The Elapsed event was raised at 09:40:39.116
// The Elapsed event was raised at 09:40:41.117
// The Elapsed event was raised at 09:40:43.132
// The Elapsed event was raised at 09:40:45.133
// The Elapsed event was raised at 09:40:47.148
//
// Terminating the application...
open System
open System.Timers
let onTimedEvent source (e: ElapsedEventArgs) =
printfn $"""The Elapsed event was raised at {e.SignalTime.ToString "HH:mm:ss.fff"}"""
// Create a timer with a two second interval.
let aTimer = new Timer 2000
// Hook up the Elapsed event for the timer.
aTimer.Elapsed.AddHandler onTimedEvent
aTimer.AutoReset <- true
aTimer.Enabled <- true
printfn "\nPress the Enter key to exit the application...\n"
printfn $"""The application started at {DateTime.Now.ToString "HH:mm:ss.fff"}"""
stdin.ReadLine() |> ignore
aTimer.Stop()
aTimer.Dispose()
printfn "Terminating the application..."
// The example displays output like the following:
// Press the Enter key to exit the application...
//
// The application started at 09:40:29.068
// The Elapsed event was raised at 09:40:31.084
// The Elapsed event was raised at 09:40:33.100
// The Elapsed event was raised at 09:40:35.100
// The Elapsed event was raised at 09:40:37.116
// The Elapsed event was raised at 09:40:39.116
// The Elapsed event was raised at 09:40:41.117
// The Elapsed event was raised at 09:40:43.132
// The Elapsed event was raised at 09:40:45.133
// The Elapsed event was raised at 09:40:47.148
//
// Terminating the application...
Imports System.Timers
Public Module Example
Private aTimer As System.Timers.Timer
Public Sub Main()
SetTimer()
Console.WriteLine("{0}Press the Enter key to exit the application...{0}",
vbCrLf)
Console.WriteLine("The application started at {0:HH:mm:ss.fff}",
DateTime.Now)
Console.ReadLine()
aTimer.Stop()
aTimer.Dispose()
Console.WriteLine("Terminating the application...")
End Sub
Private Sub SetTimer()
' Create a timer with a two second interval.
aTimer = New System.Timers.Timer(2000)
' Hook up the Elapsed event for the timer.
AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
aTimer.AutoReset = True
aTimer.Enabled = True
End Sub
' The event handler for the Timer.Elapsed event.
Private Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime)
End Sub
End Module
' The example displays output like the following:
' Press the Enter key to exit the application...
'
' The application started at 09:40:29.068
' The Elapsed event was raised at 09:40:31.084
' The Elapsed event was raised at 09:40:33.100
' The Elapsed event was raised at 09:40:35.100
' The Elapsed event was raised at 09:40:37.116
' The Elapsed event was raised at 09:40:39.116
' The Elapsed event was raised at 09:40:41.117
' The Elapsed event was raised at 09:40:43.132
' The Elapsed event was raised at 09:40:45.133
' The Elapsed event was raised at 09:40:47.148
'
' Terminating the application...
備註
這個Timer元件是一個伺服器端的計時器,會在該屬性中經過的毫秒Interval數後,在Elapsed你的應用程式中觸發一個事件。 你可以設定 Timer 物件只觸發一次事件,或是重複地用這個 AutoReset 屬性。 通常, Timer 物件會在類別層級宣告,使其在需要的時間內保持在作用域內。 你就可以處理它的 Elapsed 事件,提供定期處理。 舉例來說,假設你有一台關鍵伺服器必須全天候、每週7天持續運作。 你可以建立一個服務,使用物件 Timer 定期檢查伺服器,確保系統正常運作。 如果系統沒有回應,服務可能會嘗試重新啟動伺服器或通知管理員。
這很重要
此 Timer 類別並非適用於所有 .NET 實作與版本,例如 .NET Standard 1.6 及以下版本。 在這種情況下,你可以改用職業 System.Threading.Timer 。
此類型會實作 IDisposable 介面。 當您完成使用這個物品後,應直接或間接地處理它。 若要直接處置類型,請在 Disposetry/ 區塊中呼叫其 catch 方法。 若要間接處置它,請使用語言建構,例如 using (C#) 或 Using (在 Visual Basic 中)。 如需詳細資訊,請參閱介面主題中的
伺服器型 System.Timers.Timer 類別設計用於多執行緒環境中的工作執行緒。 伺服器計時器可在執行緒間移動以處理事件 Elapsed ,因此比 Windows 計時器更準確地按時觸發事件。
System.Timers.Timer元件根據屬性的Interval值(以毫秒計)來提升事件。Elapsed 你可以處理這個事件,完成你需要的處理。 舉例來說,假設你有一個線上銷售應用程式,持續將銷售訂單發布到資料庫中。 負責彙整出貨指令的服務是針對一批訂單進行,而非逐筆處理。 你可以用 A Timer 來每 30 分鐘開始批次處理。
這很重要
System.Timers.Timer 類別的解析度與系統時鐘相同。 這表示 Elapsed 如果該 Interval 性質小於系統時鐘的解析度,事件會在由系統時鐘解析度所定義的間隔觸發。 如需詳細資訊,請參閱 Interval 屬性 (Property)。
備註
所使用的系統時鐘與 GetTickCount 相同,且不受 timeBeginPeriod 與 timeEndPeriod 的變更影響。
當 AutoReset 設為 false時,物件 System.Timers.Timer 只會在 Elapsed 第一次 Interval 事件過後引發一次事件。 要在由 Interval定義的區間持續提升Elapsed事件,設AutoReset為true預設值。
該 Timer 元件會捕捉並抑制事件處理 Elapsed 程序拋出的所有異常。 此行為可能會在未來的 .NET Framework 版本中有所改變。 但請注意,這並不適用於非同步執行且包含 await 操作符(C#)或 Await 操作符(Visual Basic)的事件處理程序。 這些事件處理器拋出的例外會傳回呼叫執行緒,如下範例所示。 欲了解更多關於非同步方法中拋出的異常,請參見 異常處理。
using System;
using System.Threading.Tasks;
using System.Timers;
class Example
{
static void Main()
{
Timer timer = new Timer(1000);
timer.Elapsed += async ( sender, e ) => await HandleTimer();
timer.Start();
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
private static Task HandleTimer()
{
Console.WriteLine("\nHandler not implemented..." );
throw new NotImplementedException();
}
}
// The example displays output like the following:
// Press any key to exit...
// Handler not implemented...
//
// Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
// at Example.HandleTimer()
// at Example.<<Main>b__0>d__2.MoveNext()
// --- End of stack trace from previous location where exception was thrown ---
// at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
// at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
// at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
// at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
// at System.Threading.ThreadPoolWorkQueue.Dispatch()
open System
open System.Threading.Tasks
open System.Timers
let handleTimer () =
printfn "\nHandler not implemented..."
raise (NotImplementedException()): Task
let timer = new Timer 1000
timer.Elapsed.AddHandler(fun sender e -> task { do! handleTimer () } |> ignore)
timer.Start()
printf "Press any key to exit... "
Console.ReadKey() |> ignore
// The example displays output like the following:
// Press any key to exit...
// Handler not implemented...
//
// Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
// at Example.HandleTimer()
// at Example.<<Main>b__0>d__2.MoveNext()
// --- End of stack trace from previous location where exception was thrown ---
// at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
// at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
// at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
// at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
// at System.Threading.ThreadPoolWorkQueue.Dispatch()
Imports System.Threading.Tasks
Imports System.Timers
Public Module Example
Public Sub Main()
Dim timer As New Timer(1000)
AddHandler timer.Elapsed, AddressOf Example.HandleTimer
'timer.Elapsed = Async ( sender, e ) => await HandleTimer()
timer.Start()
Console.Write("Press any key to exit... ")
Console.ReadKey()
End Sub
Private Async Sub HandleTimer(sender As Object, e As EventArgs)
Await Task.Run(Sub()
Console.WriteLine()
Console.WriteLine("Handler not implemented..." )
Throw New NotImplementedException()
End Sub)
End Sub
End Module
' The example displays output like the following:
' Press any key to exit...
' Handler not implemented...
'
' Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
' at Example._Lambda$__1()
' at System.Threading.Tasks.Task.Execute()
' --- End of stack trace from previous location where exception was thrown ---
' at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
' at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
' at Example.VB$StateMachine_0_HandleTimer.MoveNext()
' --- End of stack trace from previous location where exception was thrown ---
' at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.<ThrowAsync>b__5(Object state)
' at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
' at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
' at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
' at System.Threading.ThreadPoolWorkQueue.Dispatch()
若 SynchronizingObject 屬性為 null,則 Elapsed 事件會在執行 ThreadPool 緒中被提出。 如果事件處理 Elapsed 時間超過 Interval,事件可能會在其他 ThreadPool 執行緒中再次提出。 在這種情況下,事件處理器應該是重新進入的。
備註
事件處理方法可能同時在一個執行緒執行,另一個執行緒呼叫該Stop方法或將屬性false設為 Enabled 。 這可能導致 Elapsed 計時器停止後事件被觸發。 該方法的 Stop 範例程式碼展示了一種避免此競賽條件的方法。
即使SynchronizingObject不是nullElapsed,事件也可能在 or Stop 方法被呼叫後Dispose或屬性設定false為 Enabled 後發生,因為事件Elapsed引發的訊號總是排隊執行於執行緒池執行緒中。 解決此競賽條件的一種方法是設定一個旗標,告訴事件處理 Elapsed 程序忽略後續事件。
如果你使用 System.Timers.Timer 帶有使用者介面元素(如表單或控制項)的類別,且未將計時器放在該使用者介面元素上,請將包含該 Timer 的表單或控制項指派到 SynchronizingObject 該屬性,使事件被編入使用者介面執行緒。
小提示
.NET 包含四個名為 Timer的類別,每個類別提供不同的功能:
- System.Timers.Timer (本主題):定期觸發事件。 此類別設計用於多執行緒環境中作為伺服器端或服務元件;它沒有使用者介面,執行時也無法顯示。
- System.Threading.Timer: 在執行緒池執行緒上以固定間隔執行單一回調方法。 回調方法定義於計時器實例化且無法更改時。 與類別 System.Timers.Timer 相同,此類別設計用於多執行緒環境中作為伺服器端或服務元件;它沒有使用者介面,執行時不可見。
- System.Windows.Forms.Timer:定期引發事件的 Windows Forms 元件。 元件沒有使用者介面,且設計用於單個線程環境中。
- System.Web.UI.Timer (僅限 .NET Framework):一個 ASP.NET 元件,定期執行非同步網頁回貼。
建構函式
| 名稱 | Description |
|---|---|
| Timer() |
初始化該類別的新實例 Timer ,並將所有屬性設定為初始值。 |
| Timer(Double) | |
| Timer(TimeSpan) |
屬性
| 名稱 | Description |
|---|---|
| AutoReset | |
| CanRaiseEvents |
會得到一個值,表示該元件是否能引發事件。 (繼承來源 Component) |
| Container |
得到 IContainer 包含 Component的 。 (繼承來源 Component) |
| DesignMode |
會得到一個值,表示目前 Component 是否處於設計模式。 (繼承來源 Component) |
| Enabled | |
| Events |
會取得與此 Component連結的事件處理程序清單。 (繼承來源 Component) |
| Interval |
取得或設定以毫秒表示的事件升高 Elapsed 間隔。 |
| Site |
取得或設定將 綁 Timer 定為其容器的網站,並以設計模式的方式。 |
| SynchronizingObject |
取得或設定用於在間隔結束時發出的事件處理呼叫的物件。 |
方法
| 名稱 | Description |
|---|---|
| BeginInit() |
開始執行時初始化 a Timer 的表單或其他元件所使用的 。 |
| Close() |
釋放 所使用的 Timer資源。 |
| CreateObjRef(Type) |
建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。 (繼承來源 MarshalByRefObject) |
| Dispose() |
釋放所有由 Component. (繼承來源 Component) |
| Dispose(Boolean) |
釋放目前 Timer所有已使用的資源。 |
| EndInit() |
結束執行時初始化,該 a Timer 用於表單或其他元件。 |
| Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
| GetHashCode() |
做為預設哈希函式。 (繼承來源 Object) |
| GetLifetimeService() |
已淘汰.
取得目前控制此實例生命週期政策的終身服務物件。 (繼承來源 MarshalByRefObject) |
| GetService(Type) |
回傳一個由 或Component其 所提供的Container服務的物件。 (繼承來源 Component) |
| GetType() |
取得目前實例的 Type。 (繼承來源 Object) |
| InitializeLifetimeService() |
已淘汰.
取得一個終身服務物件以控制此實例的終身政策。 (繼承來源 MarshalByRefObject) |
| MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
| MemberwiseClone(Boolean) |
建立一個 MarshalByRefObject 目前物件的淺層複製品。 (繼承來源 MarshalByRefObject) |
| Start() | |
| Stop() | |
| ToString() |
回傳 String 包含 的名稱 Component(若有的話)。 此方法不應被覆蓋。 (繼承來源 Component) |
事件
| 名稱 | Description |
|---|---|
| Disposed |
當元件被呼叫方法 Dispose() 時會發生。 (繼承來源 Component) |
| Elapsed |
當間隔結束時發生。 |
適用於
執行緒安全性
這類公開 static 成員都是安全的。 任何實例成員都不保證具有執行緒安全性。