Timer 類別

定義

使用產生週期性事件的選項,在設定的間隔後產生事件。

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 每兩秒引發其 Timer.Elapsed 事件的 物件, (2,000 毫秒) 、設定事件的事件處理常式,然後啟動計時器。 事件處理常式會在每次引發屬性時顯示其值 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 事件,以提供一般處理。 例如,假設您有一部重要的伺服器必須持續執行一天 24 小時,一周 7 天。 您可以建立使用 Timer 物件定期檢查伺服器的服務,並確保系統已啟動並執行。 如果系統未回應,服務可能會嘗試重新開機伺服器或通知系統管理員。

重要

類別 Timer 不適用於所有 .NET 實作和版本,例如 .NET Standard 1.6 和更低版本。 在這些情況下,您可以改用 System.Threading.Timer 類別。

此型別代表 IDisposable 介面。 當您完成使用型別時,您應該直接或間接處置它。 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。

伺服器型 System.Timers.Timer 類別的設計目的是要與多執行緒環境中的背景工作執行緒搭配使用。 伺服器計時器可以線上程之間移動以處理引發 Elapsed 的事件,導致比 Windows 計時器更精確的時間引發事件。

元件 ElapsedSystem.Timers.Timer 根據 屬性) 毫秒 Interval 的值 (引發事件。 您可以處理此事件來執行所需的處理。 例如,假設您有一個線上銷售應用程式會持續將銷售訂單張貼至資料庫。 編譯出貨指令的服務會在訂單批次上運作,而不是個別處理每個訂單。 您可以使用 Timer 來每隔 30 分鐘啟動批次處理一次。

重要

System.Timers.Timer 類別的解析度與系統時鐘相同。 這表示 Elapsed 如果 Interval 屬性小於系統時鐘的解析度,事件會以系統時鐘的解析所定義的間隔引發。 如需詳細資訊,請參閱 Interval 屬性 (Property)。

注意

所使用的系統時鐘是 GetTickCount所使用的相同時鐘,這不會受到 timeBeginPeriodtimeEndPeriod所做的變更所影響。

當 設定為 時 AutoResetSystem.Timers.Timer 物件只會在第一 Interval 次經過之後引發 Elapsed 事件一次。 false 若要在 所 Interval 定義的間隔中定期引發 Elapsed 事件,請將 設定 AutoResettrue ,這是預設值。

元件 Timer 會攔截並隱藏事件事件處理常式 Elapsed 擲回的所有例外狀況。 此行為在.NET Framework的未來版本中可能會變更。 不過請注意,這不是以非同步方式執行的事件處理常式,而且在 C#) 中包含 await 運算子 (,或 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 ,則會 ElapsedThreadPool 執行緒上引發 事件。 如果事件的處理 Elapsed 時間超過 Interval ,則事件可能會在另一個 ThreadPool 執行緒上再次引發。 在此情況下,事件處理常式應該重新進入。

注意

事件處理方法可能會在一個執行緒上執行,而另一個執行緒會呼叫 Stop 方法,或將 Enabled 屬性設定為 false 。 這可能會導致 Elapsed 在計時器停止之後引發事件。 方法的 Stop 範例程式碼示範一種方式,以避免這種競爭狀況。

即使 不是 ,在 呼叫 或 Stop 方法之後 Dispose ,或 屬性設定 false 為 之後 Enabled ,就會發生事件,因為引發 Elapsed 事件的訊號一律排入佇列,以線上程集區執行緒上執行。 ElapsednullSynchronizingObject 解決此競爭條件的其中一種方式是設定旗標,告知事件的事件處理常式 Elapsed 忽略後續事件。

如果您使用 System.Timers.Timer 類別搭配使用者介面元素,例如表單或控制項,而不將計時器放在該使用者介面元素上,請將包含 Timer 的表單或控制項指派給 SynchronizingObject 屬性,讓事件封送處理至使用者介面執行緒。

如需 實例 Timer 的預設屬性值清單,請參閱 建 Timer 構函式。

提示

.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 元件。

建構函式

Timer()

初始化 Timer 類別的新執行個體,並將所有屬性設為其初始值。

Timer(Double)

初始化 Timer 類別的新執行個體,並將 Interval 屬性設定為指定的毫秒數。

Timer(TimeSpan)

初始化 類別的新實例 Timer ,並將 Interval 屬性設定為指定的句點。

屬性

AutoReset

取得或設定布林值,表示 Timer 是否應該只引發 Elapsed 事件一次 (false) 或重複 (true)。

CanRaiseEvents

取得值,指出元件是否能引發事件。

(繼承來源 Component)
Container

取得包含 IContainerComponent

(繼承來源 Component)
DesignMode

取得值,指出 Component 目前是否處於設計模式。

(繼承來源 Component)
Enabled

取得或設定值,表示 Timer 是否應引發 Elapsed 事件。

Events

取得附加在這個 Component 上的事件處理常式清單。

(繼承來源 Component)
Interval

取得或設定引發 Elapsed 事件的間隔 (以毫秒為單位)。

Site

取得或設定在設計模式中繫結 Timer 到其容器的站台。

SynchronizingObject

取得或設定物件,用來封送處理事件處理常式的呼叫 (當間隔已經耗盡時所發出)。

方法

BeginInit()

開始用於表單或為另一個元件所使用之 Timer 的執行階段初始化。

Close()

釋放 Timer 使用的資源。

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
Dispose()

釋放 Component 所使用的所有資源。

(繼承來源 Component)
Dispose(Boolean)

釋放目前 Timer 所使用的所有資源。

EndInit()

結束用於表單或為另一個元件所使用之 Timer 的執行階段初始化。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetService(Type)

傳回表示 Component 或其 Container 所提供之服務的物件。

(繼承來源 Component)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個執行個體的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。

(繼承來源 MarshalByRefObject)
Start()

Enabled 設定為 true,開始引發 Elapsed 事件。

Stop()

Enabled 設定為 false,停止引發 Elapsed 事件。

ToString()

傳回任何包含 Component 名稱的 String。 不應覆寫此方法。

(繼承來源 Component)

事件

Disposed

Dispose() 方法的呼叫處置元件時,就會發生。

(繼承來源 Component)
Elapsed

發生於間隔耗盡時。

適用於

執行緒安全性

此類型的任何公用 static 成員都是安全線程。 並非所有的執行個體成員都是安全執行緒。

另請參閱