Timer类:

在设定的间隔之后生成事件,带有生成重复事件的选项。

若要浏览此类型的 .NET Framework 源代码,请参阅引用源

命名空间:                   System.Timers
程序集:         System(位于 System.dll)

继承层次结构

System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Timers.Timer

语法:

[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
	public class Timer : Component, ISupportInitialize

构造函数


名称说明
System_CAPS_pubmethodTimer()

初始化 Timer 类的新实例,并将所有属性设置为初始值。

System_CAPS_pubmethodTimer(Double)

初始化 Timer 类的新实例,并将 Interval 属性设置为指定的毫秒数。

属性


名称说明
System_CAPS_pubpropertyAutoReset

获取或设置一个布尔值,该值指示 Timer 是否应只引发一次 Elapsed 事件((false) 或重复 (true))。

System_CAPS_protpropertyCanRaiseEvents

获取一个值,该值指示组件是否可以引发一个事件。(继承自 Component。)

System_CAPS_pubpropertyContainer

获取 IContainer ,其中包含 Component(继承自 Component。)

System_CAPS_protpropertyDesignMode

获取一个值,该值指示是否 Component 当前处于设计模式。(继承自 Component。)

System_CAPS_pubpropertyEnabled

获取或设置一个值,该值指示 Timer 是否应引发 Elapsed 事件。

System_CAPS_protpropertyEvents

获取的事件处理程序附加到此列表 Component(继承自 Component。)

System_CAPS_pubpropertyInterval

获取或设置引发 Elapsed 事件的间隔(以毫秒为单位)。

System_CAPS_pubpropertySite

此 API 支持 产品 基础结构,不应从代码直接使用。      获取或设置在设计模式中将 Timer 绑定到其容器的站点。(覆盖 Component.Site。)

System_CAPS_pubpropertySynchronizingObject

获取或设置对象,该对象用于在间隔过后封送发出的事件处理程序调用。

方法


名称说明
System_CAPS_pubmethodBeginInit()

开始用于窗体或由其他组件使用的 Timer 的运行时初始化。

System_CAPS_pubmethodClose()

释放由 Timer 占用的资源。

System_CAPS_pubmethodCreateObjRef(Type)

创建包含生成用来与远程对象通信的代理所需的所有相关信息的对象。(继承自 MarshalByRefObject。)

System_CAPS_pubmethodDispose()

释放由 Component 使用的所有资源。(继承自 Component。)

System_CAPS_protmethodDispose(Boolean)

此 API 支持 产品 基础结构,不应从代码直接使用。      释放由当前 Timer 使用的所有资源。(覆盖 Component.Dispose(Boolean)。)

System_CAPS_pubmethodEndInit()

结束用于窗体或由其他组件使用的 Timer 的运行时初始化。

System_CAPS_pubmethodEquals(Object)

确定指定的对象是否等于当前对象。(继承自 Object。)

System_CAPS_protmethodFinalize()

在通过垃圾回收将 Component 回收之前,释放非托管资源并执行其他清理操作。(继承自 Component。)

System_CAPS_pubmethodGetHashCode()

作为默认哈希函数。(继承自 Object。)

System_CAPS_pubmethodGetLifetimeService()

检索当前生存期的服务对象,用于控制此实例的生存期策略。(继承自 MarshalByRefObject。)

System_CAPS_protmethodGetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。(继承自 Component。)

System_CAPS_pubmethodGetType()

获取当前实例的 Type(继承自 Object。)

System_CAPS_pubmethodInitializeLifetimeService()

获取使用生存期服务对象来控制此实例的生存期策略。(继承自 MarshalByRefObject。)

System_CAPS_protmethodMemberwiseClone()

创建当前 Object 的浅表副本。(继承自 Object。)

System_CAPS_protmethodMemberwiseClone(Boolean)

创建当前的浅表副本 MarshalByRefObject 对象。(继承自 MarshalByRefObject。)

System_CAPS_pubmethodStart()

通过将 Enabled 设置为 true 开始引发 Elapsed 事件。

System_CAPS_pubmethodStop()

通过将 Enabled 设置为 false 停止引发 Elapsed 事件。

System_CAPS_pubmethodToString()

返回 String 包含名称的 Component, ,如果有的话。 不应重写此方法。(继承自 Component。)

事件


名称说明
System_CAPS_pubeventDisposed

通过调用释放组件时发生 Dispose 方法。(继承自 Component。)

System_CAPS_pubeventElapsed

达到间隔时发生。

备注

System_CAPS_note说明

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#System/services/timers/system/timers/Timer.cs#897683f27faba082. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

The T:System.Timers.Timer component is a server-based timer that raises an E:System.Timers.Timer.Elapsed event in your application after the number of milliseconds in the P:System.Timers.Timer.Interval property has elapsed. You can configure the T:System.Timers.Timer object to raise the event just once or repeatedly using the P:System.Timers.Timer.AutoReset property. Typically, a T:System.Timers.Timer object is declared at the class level so that it stays in scope as long as it is needed. You can then handle its E:System.Timers.Timer.Elapsed event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a T:System.Timers.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.

System_CAPS_important重要事项

The T:System.Timers.Timer class is available in the .NET Framework only. It is not included in the .NET Standard Library and is not available on other platforms, such as .NET Core or the Universal Windows Platform. On these platforms, as well as for portability across all .NET platforms, you should use the T:System.Threading.Timer class instead.

This type implements the T:System.IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its M:System.IDisposable.Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the T:System.IDisposable interface topic.

The server-based T:System.Timers.Timer class is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised E:System.Timers.Timer.Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

The T:System.Timers.Timer component raises the E:System.Timers.Timer.Elapsed event, based on the value (in milliseconds) of the P:System.Timers.Timer.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. You could use a T:System.Timers.Timer to start the batch processing every 30 minutes.

System_CAPS_important重要事项

The System.Timers.Timer class has the same resolution as the system clock. This means that the E:System.Timers.Timer.Elapsed event will fire at an interval defined by the resolution of the system clock if the P:System.Timers.Timer.Interval property is less than the resolution of the system clock. For more information, see the P:System.Timers.Timer.Interval property.

When P:System.Timers.Timer.AutoReset is set to false, a T:System.Timers.Timer object raises the E:System.Timers.Timer.Elapsed event only once, after the first P:System.Timers.Timer.Interval has elapsed. To keep raising the E:System.Timers.Timer.Elapsed event regularly at the interval defined by the P:System.Timers.Timer.Interval, set P:System.Timers.Timer.AutoReset to true, which is the default value.

The T:System.Timers.Timer component catches and suppresses all exceptions thrown by event handlers for the E:System.Timers.Timer.Elapsed event. This behavior is subject to change in future releases of the .NET Framework. 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 (Task Parallel Library)【任务并行库】.

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__DisplayClass
2.<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()

If the P:System.Timers.Timer.SynchronizingObject property is null, the E:System.Timers.Timer.Elapsed event is raised on a T:System.Threading.ThreadPool thread. If processing of the E:System.Timers.Timer.Elapsed event lasts longer than P:System.Timers.Timer.Interval, the event might be raised again on another T:System.Threading.ThreadPool thread. In this situation, the event handler should be reentrant【凹角,再进入】.

说明:

The event-handling method might run on one thread at the same time that another thread calls the M:System.Timers.Timer.Stop method or sets the P:System.Timers.Timer.Enabled property to false. This might result in the E:System.Timers.Timer.Elapsed event being raised after the timer is stopped. The example code for the M:System.Timers.Timer.Stop method shows one way to avoid this race condition.

Even if P:System.Timers.Timer.SynchronizingObject is not null, E:System.Timers.Timer.Elapsed events can occur after the Overload:System.Timers.Timer.Dispose or M:System.Timers.Timer.Stop method has been called or after the P:System.Timers.Timer.Enabled property has been set to false, because the signal to raise the E:System.Timers.Timer.Elapsed event is always queued for execution on a thread pool thread. One way to resolve this race condition is to set a flag that tells the event handler for the E:System.Timers.Timer.Elapsed event to ignore subsequent events.

If you use the T: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 T:System.Timers.Timer to the P:System.Timers.Timer.SynchronizingObject property, so that the event is marshaled to the user interface thread.

For a list of default property values for an instance of T:System.Timers.Timer, see the M:System.Timers.Timer.#ctor constructor.

Be aware that the .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • 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: 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. 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: 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: an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.


The following example instantiates a System.Timers.Timer object that fires its E:System.Timers.Timer.Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the  event, and starts the timer. The event handler displays the value of the P:System.Timers.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...

备注:转自https://msdn.microsoft.com/zh-cn/library/system.timers.timer(v=vs.110).aspx