Timer Timer Timer Timer Class

定義

使用產生週期性事件的選項,在設定的間隔後產生事件。Generates an event after a set interval, with an option to generate recurring events.

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引發其事件的物件 (2000 毫秒), 設定事件的事件處理常式, 並啟動計時器。The following example instantiates a System.Timers.Timer object that fires its Timer.Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the event, and starts the timer. 事件處理常式會在每次引發ElapsedEventArgs.SignalTime時顯示內容的值。The event handler displays the value of the ElapsedEventArgs.SignalTime property each time it is raised.

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...
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...

備註

元件是以伺服器為基礎的計時器, 會在Elapsed Interval屬性中的毫秒數經過之後, 在您的應用程式中引發事件。 TimerThe Timer component is a server-based timer that raises an Elapsed event in your application after the number of milliseconds in the Interval property has elapsed. 您可以設定Timer物件只AutoReset使用屬性來引發事件一次或重複。You can configure the Timer object to raise the event just once or repeatedly using the AutoReset property. 一般而言, Timer物件是在類別層級宣告, 因此只要需要, 它就會保留在範圍中。Typically, a Timer object is declared at the class level so that it stays in scope as long as it is needed. 接著, 您可以處理Elapsed其事件以提供一般處理。You can then handle its Elapsed event to provide regular processing. 例如, 假設您有一台必須持續執行24小時、一周7天的重要伺服器。For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. 您可以建立一個服務, 使用Timer物件來定期檢查伺服器, 並確定系統已啟動且正在執行。You could create a service that uses a Timer object to periodically check the server and ensure that the system is up and running. 如果系統沒有回應, 服務可能會嘗試重新開機伺服器或通知系統管理員。If the system is not responding, the service could attempt to restart the server or notify an administrator.

重要

Timer類別不適用於所有的 .net 部署和版本, 例如 .NET Standard 1.6 和較舊版本。The Timer class is not available for all .NET implementations and versions, such as .NET Standard 1.6 and lower versions. 在這些情況下, 您可以System.Threading.Timer改用類別。In these cases, you can use the System.Threading.Timer class instead.

此型別代表 IDisposable 介面。This type implements the IDisposable interface. 當您完成使用型別時,您應該直接或間接處置它。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

以伺服器為基礎System.Timers.Timer的類別是設計用來與多執行緒環境中的背景工作執行緒搭配使用。The server-based System.Timers.Timer class is designed for use with worker threads in a multithreaded environment. 伺服器計時器可以線上程之間移動以處理引發Elapsed的事件, 導致比 Windows 計時器準時引發事件的精確度更高。Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

元件會根據Interval屬性Elapsed的值 (以毫秒為單位), 引發事件。 System.Timers.TimerThe System.Timers.Timer component raises the Elapsed event, based on the value (in milliseconds) of the Interval property. 您可以處理這個事件來執行所需的處理。You can handle this event to perform the processing you need. 例如, 假設您的線上銷售應用程式會持續將銷售訂單張貼到資料庫。For example, suppose that you have an online sales application that continuously posts sales orders to a database. 用來編譯運送指示的服務會在一批訂單上運作, 而不是個別處理每個訂單。The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. 您可以使用Timer , 每隔30分鐘啟動批次處理。You could use a Timer to start the batch processing every 30 minutes.

重要

Timer 類別與系統時鐘具有相同的解析度。The System.Timers.Timer class has the same resolution as the system clock. 這表示, Interval如果Elapsed屬性小於系統時鐘的解析度, 則會以系統時鐘解析所定義的間隔來觸發事件。This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock. 如需詳細資訊,請參閱 Interval 屬性 (Property)。For more information, see the Interval property.

AutoReset設定為falseSystem.Timers.Timer ,物件Interval只會在經過第一個事件之後引發一次事件。ElapsedWhen AutoReset is set to false, a System.Timers.Timer object raises the Elapsed event only once, after the first Interval has elapsed. 若要持續以Elapsed所定義Interval的間隔來定期引發事件, 請AutoResettrue設定為, 這是預設值。To keep raising the Elapsed event regularly at the interval defined by the Interval, set AutoReset to true, which is the default value.

元件會攔截並隱藏事件的事件處理常式所Elapsed擲回的所有例外狀況。 TimerThe Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. 在未來的 .NET Framework 版本中, 此行為可能會有所變更。This behavior is subject to change in future releases of the .NET Framework. 不過, 請注意, 這不是以非同步方式執行並包含await運算子 (在中C#) 或Await運算子 (在 Visual Basic 中) 的事件處理常式。Note, however, that this is not true of event handlers that execute asynchronously and include the await operator (in C#) or the Await operator (in Visual Basic). 在這些事件處理常式中擲回的例外狀況會傳播回到呼叫執行緒, 如下列範例所示。Exceptions thrown in these event handlers are propagated back to the calling thread, as the following example illustrates. 如需非同步方法中擲回之例外狀況的詳細資訊, 請參閱例外狀況處理For more information on exceptions thrown in asynchronous methods, see Exception Handling.

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()
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()

如果屬性為null, 則Elapsed會在ThreadPool執行緒上引發事件。 SynchronizingObjectIf the SynchronizingObject property is null, the Elapsed event is raised on a ThreadPool thread. 如果Elapsed事件的處理持續時間超過Interval, 則事件可能會在另一個ThreadPool執行緒上再次引發。If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. 在此情況下, 事件處理常式應該是可重新進入的。In this situation, the event handler should be reentrant.

注意

事件處理方法可能會在另一個執行緒呼叫Stop方法或Enabled將屬性設定為false的同時, 于一個執行緒上執行。The event-handling method might run on one thread at the same time that another thread calls the Stop method or sets the Enabled property to false. 這可能會導致Elapsed在計時器停止後引發事件。This might result in the Elapsed event being raised after the timer is stopped. Stop方法的範例程式碼顯示一個避免此競爭條件的方法。The example code for the Stop method shows one way to avoid this race condition.

Dispose即使不SynchronizingObject Enabled false是, 在呼叫或Stop方法之後, 或屬性設定為之後, 才會發生事件, 因為信號會引發Elapsed null Elapsed事件一律會排入佇列, 以便線上程集區執行緒上執行。Even if SynchronizingObject is not null, Elapsed events can occur after the Dispose or Stop method has been called or after the Enabled property has been set to false, because the signal to raise the Elapsed event is always queued for execution on a thread pool thread. 解決此競爭條件的其中一種方法是設定旗標, 告知事件處理常式事件Elapsed是否忽略後續事件。One way to resolve this race condition is to set a flag that tells the event handler for the Elapsed event to ignore subsequent events.

如果您使用System.Timers.Timer類別搭配使用者介面專案 (例如表單或控制項), 而不將計時器放在該使用者介面專案上, 請將包含的Timer表單或控制項指派給SynchronizingObject屬性, 讓事件成為封送處理至使用者介面執行緒。If you use the System.Timers.Timer class with a user interface element, such as a form or control, without placing the timer on that user interface element, assign the form or control that contains the Timer to the SynchronizingObject property, so that the event is marshaled to the user interface thread.

如需實例的Timer預設屬性值清單, Timer請參閱函數。For a list of default property values for an instance of Timer, see the Timer constructor.

提示

請注意, .net 包含四個名Timer為的類別, 其中每一個都提供不同的功能:Be aware that .NET includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer(本主題): 定期引發事件。System.Timers.Timer (this topic): fires an event at regular intervals. 類別是用來做為多執行緒環境中的伺服器型或服務元件;它沒有使用者介面, 而且在執行時間看不到。The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer: 線上程集區執行緒上定期執行單一回呼方法。System.Threading.Timer: executes a single callback method on a thread pool thread at regular intervals. 當計時器已具現化且無法變更時, 會定義回呼方法。The callback method is defined when the timer is instantiated and cannot be changed. 就像System.Timers.Timer類別一樣, 這個類別是用來做為多執行緒環境中的伺服器型或服務元件; 它沒有使用者介面, 而且在執行時間看不到。Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer(僅限 .NET Framework): 定期引發事件的 Windows Forms 元件。System.Windows.Forms.Timer (.NET Framework only): a Windows Forms component that fires an event at regular intervals. 該元件沒有使用者介面,是專為用於單一執行緒環境所設計。The component has no user interface and is designed for use in a single-threaded environment.
  • System.Web.UI.Timer(僅限 .NET Framework): 以固定間隔執行非同步或同步網頁回傳的 ASP.NET 元件。System.Web.UI.Timer (.NET Framework only): an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

建構函式

Timer() Timer() Timer() Timer()

初始化 Timer 類別的新執行個體,並將所有屬性設為其初始值。Initializes a new instance of the Timer class, and sets all the properties to their initial values.

Timer(Double) Timer(Double) Timer(Double) Timer(Double)

初始化 Timer 類別的新執行個體,並將 Interval 屬性設定為指定的毫秒數。Initializes a new instance of the Timer class, and sets the Interval property to the specified number of milliseconds.

屬性

AutoReset AutoReset AutoReset AutoReset

取得或設定布林值,表示 Timer 是否應該只引發 Elapsed 事件一次 (false) 或重複 (true)。Gets or sets a Boolean indicating whether the Timer should raise the Elapsed event only once (false) or repeatedly (true).

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

取得值,指出元件是否能引發事件。Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container Container Container Container

取得包含 IContainerComponentGets the IContainer that contains the Component.

(Inherited from Component)
DesignMode DesignMode DesignMode DesignMode

取得值,指出 Component 目前是否處於設計模式。Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Enabled Enabled Enabled Enabled

取得或設定值,表示 Timer 是否應引發 Elapsed 事件。Gets or sets a value indicating whether the Timer should raise the Elapsed event.

Events Events Events Events

取得附加在這個 Component 上的事件處理常式清單。Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Interval Interval Interval Interval

取得或設定引發 Elapsed 事件的間隔 (以毫秒為單位)。Gets or sets the interval, expressed in milliseconds, at which to raise the Elapsed event.

Site Site Site Site

取得或設定在設計模式中繫結 Timer 到其容器的站台。Gets or sets the site that binds the Timer to its container in design mode.

SynchronizingObject SynchronizingObject SynchronizingObject SynchronizingObject

取得或設定物件,用來封送處理事件處理常式的呼叫 (當間隔已經耗盡時所發出)。Gets or sets the object used to marshal event-handler calls that are issued when an interval has elapsed.

方法

BeginInit() BeginInit() BeginInit() BeginInit()

開始用於表單或為另一個元件所使用之 Timer 的執行階段初始化。Begins the run-time initialization of a Timer that is used on a form or by another component.

Close() Close() Close() Close()

釋放 Timer 使用的資源。Releases the resources used by the Timer.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

釋放 Component 所使用的所有資源。Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

釋放目前 Timer 所使用的所有資源。Releases all resources used by the current Timer.

EndInit() EndInit() EndInit() EndInit()

結束用於表單或為另一個元件所使用之 Timer 的執行階段初始化。Ends the run-time initialization of a Timer that is used on a form or by another component.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

傳回表示 Component 或其 Container 所提供之服務的物件。Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Start() Start() Start() Start()

Enabled 設定為 true,開始引發 Elapsed 事件。Starts raising the Elapsed event by setting Enabled to true.

Stop() Stop() Stop() Stop()

Enabled 設定為 false,停止引發 Elapsed 事件。Stops raising the Elapsed event by setting Enabled to false.

ToString() ToString() ToString() ToString()

傳回任何包含 Component 名稱的 StringReturns a String containing the name of the Component, if any. 不應覆寫此方法。This method should not be overridden.

(Inherited from Component)

事件

Disposed Disposed Disposed Disposed

當此元件由 Dispose() 方法的呼叫處置時發生。Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
Elapsed Elapsed Elapsed Elapsed

發生於間隔耗盡時。Occurs when the interval elapses.

適用於

執行緒安全性

這種static類型的任何公用成員都是安全線程。Any public static members of this type are thread safe. 不保證任何執行個體成員是安全執行緒。Any instance members are not guaranteed to be thread safe.

另請參閱