Timer 类

定义

在设定的间隔之后生成事件,带有生成重复事件的选项。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.SignalTimeThe 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...

注解

Timer组件是一个基于服务器的计时器,在 Elapsed 属性中的毫秒数后,在应用程序中引发事件 IntervalThe 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 对象配置为只引发一次事件,或使用属性重复一次 AutoResetYou 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. 例如,假设你有一个关键服务器,该服务器必须每周7天、每天24小时保持运行。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.

组件将根据 System.Timers.Timer Elapsed 属性的值 (以毫秒) 来引发事件 IntervalThe 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.

重要

系统定时器类的分辨率与系统时钟相同。The System.Timers.Timer class has the same resolution as the system clock. 这意味着, Elapsed 如果 Interval 属性小于系统时钟的分辨率,则将以系统时钟解析定义的间隔触发事件。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 属性。For more information, see the Interval property.

AutoReset 设置为时 falseSystem.Timers.Timer 对象在 Elapsed 第一次运行后仅引发一次事件 IntervalWhen 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.

Timer组件捕获并取消事件的事件处理程序引发的所有异常 ElapsedThe 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) 中的 operator (。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()

如果 SynchronizingObject 属性为 null ,则在 Elapsed 线程上引发事件 ThreadPoolIf the SynchronizingObject property is null, the Elapsed event is raised on a ThreadPool thread. 如果事件的处理 Elapsed 持续时间超过 Interval ,则可能会在另一个线程上再次引发该事件 ThreadPoolIf 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 属性设置为 falseThe 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.

即使不 SynchronizingObjectnull ,在 Elapsed Dispose 调用或方法之后或属性设置为之后,也可能会发生事件 Stop Enabled false ,因为引发事件的信号 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 窗体组件。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 类的新实例,并将所有属性设置为初始值。Initializes a new instance of the Timer class, and sets all the properties to their initial values.

Timer(Double)

初始化 Timer 类的新实例,并将 Interval 属性设置为指定的毫秒数。Initializes a new instance of the Timer class, and sets the Interval property to the specified number of milliseconds.

属性

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

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(继承自 Component)
Container

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

(继承自 Component)
DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(继承自 Component)
Enabled

获取或设置一个值,该值指示 Timer 是否应引发 Elapsed 事件。Gets or sets a value indicating whether the Timer should raise the Elapsed event.

Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(继承自 Component)
Interval

获取或设置引发 Elapsed 事件的间隔(以毫秒为单位)。Gets or sets the interval, expressed in milliseconds, at which to raise the Elapsed event.

Site

获取或设置在设计模式中将 Timer 绑定到其容器的站点。Gets or sets the site that binds the Timer to its container in design mode.

SynchronizingObject

获取或设置对象,该对象用于在间隔过后封送发出的事件处理程序调用。Gets or sets the object used to marshal event-handler calls that are issued when an interval has elapsed.

方法

BeginInit()

开始用于窗体或由其他组件使用的 Timer 的运行时初始化。Begins the run-time initialization of a Timer that is used on a form or by another component.

Close()

释放由 Timer 占用的资源。Releases the resources used by the Timer.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(继承自 Component)
Dispose(Boolean)

释放由当前 Timer 使用的所有资源。Releases all resources used by the current Timer.

EndInit()

结束用于窗体或由其他组件使用的 Timer 的运行时初始化。Ends the run-time initialization of a Timer that is used on a form or by another component.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()
已过时。

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(继承自 Component)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()
已过时。

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
Start()

通过将 Enabled 设置为 true 开始引发 Elapsed 事件。Starts raising the Elapsed event by setting Enabled to true.

Stop()

通过将 Enabled 设置为 false 停止引发 Elapsed 事件。Stops raising the Elapsed event by setting Enabled to false.

ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(继承自 Component)

事件

Disposed

在通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(继承自 Component)
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.

另请参阅