Timer 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
在设定的间隔之后生成事件,带有生成重复事件的选项。
public ref class Timer : System::ComponentModel::Component, System::ComponentModel::ISupportInitializepublic class Timer : System.ComponentModel.Component, System.ComponentModel.ISupportInitializetype Timer = class
    inherit Component
    interface ISupportInitializePublic 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 事件以提供常规处理。 例如,假设关键服务器必须保持每周 7 天、每天 24 小时运行。 可以创建一个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 计时器更准确。
组件System.Timers.TimerElapsed根据 属性) 的值 (毫秒Interval引发 事件。 可以处理此事件以执行所需的处理。 例如,假设你有一个将销售订单持续发布到数据库的联机销售应用程序。 编译发货说明的服务对一批订单进行操作,而不是单独处理每个订单。 可以使用 Timer 每 30 分钟启动一次批处理。
重要
System.Timers.Timer 类的分辨率与系统时钟相同。 这意味着, Elapsed 如果 Interval 属性小于系统时钟的分辨率,事件将按系统时钟的分辨率定义的时间间隔触发。 有关更多信息,请参见 Interval 属性。
注意
所使用的系统时钟与 GetTickCount 使用的时钟相同,不受 timeBeginPeriod 和 timeEndPeriod 所做的更改的影响。
当 设置为 时AutoReset,对象仅在第Interval一System.Timers.Timer个 经过后引发Elapsed事件一false次。 若要在 定义的Interval时间间隔内定期引发Elapsed事件,请将 设置为 AutoResettrue,这是默认值。
组件 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 该方法或将 Enabled 属性设置为 false的同时在一个线程上运行。 这可能会导致 Elapsed 在计时器停止后引发 事件。 方法的示例代码 Stop 演示了避免此争用条件的一种方法。
即使不是 ,事件也可能发生在调用 或 Stop 方法后Dispose或 属性设置为 false之后Enabled,因为引发Elapsed事件的信号始终在线程池线程上排队等待执行。 ElapsednullSynchronizingObject 解决此争用条件的一种方法是设置一个标志,告知事件的事件处理程序 Elapsed 忽略后续事件。
如果将 类与用户界面元素(如窗体或控件)一起使用System.Timers.Timer,而不在该用户界面元素上放置计时器,请将包含 的TimerSynchronizingObject窗体或控件分配给 属性,以便将事件封送到用户界面线程。
有关 实例 Timer的默认属性值的列表, Timer 请参阅 构造函数。
提示
.NET 包括四个名为 Timer的类,每个类提供不同的功能:
- System.Timers.Timer (本主题) :定期触发事件。 类旨在用作多线程环境中的基于服务器或服务组件;它没有用户界面,在运行时不可见。
- System.Threading.Timer:定期在线程池线程上执行单个回调方法。 回调方法是在实例化计时器时定义的,并且无法更改。 System.Timers.Timer与 类一样,此类旨在用作多线程环境中的基于服务器或服务组件;它没有用户界面,在运行时不可见。
- System.Windows.Forms.Timer:一种 Windows 窗体组件,按固定时间间隔触发事件。 该组件没有用户界面,专门用于单线程环境。
- System.Web.UI.Timer (.NET Framework仅) :定期执行异步或同步网页回发的 ASP.NET 组件。
构造函数
| Timer() | 初始化 Timer 类的新实例,并将所有属性设置为初始值。 | 
| Timer(Double) | |
| Timer(TimeSpan) | 
属性
| AutoReset | 获取或设置一个布尔值,该值指示 Timer 是否应只引发一次 Elapsed 事件(( | 
| CanRaiseEvents | 获取一个指示组件是否可以引发事件的值。(继承自 Component) | 
| Container | 获取包含 IContainer 的 Component。(继承自 Component) | 
| DesignMode | 获取一个值,用以指示 Component 当前是否处于设计模式。(继承自 Component) | 
| Enabled | |
| Events | 获取附加到此 Component 的事件处理程序的列表。(继承自 Component) | 
| Interval | 获取或设置引发 Elapsed 事件的间隔(以毫秒为单位)。 | 
| Site | 获取或设置在设计模式中将 Timer 绑定到其容器的站点。 | 
| SynchronizingObject | 获取或设置对象,该对象用于在间隔过后封送发出的事件处理程序调用。 | 
方法
| BeginInit() | 开始用于窗体或由其他组件使用的 Timer 的运行时初始化。 | 
| Close() | 释放由 Timer 占用的资源。 | 
| CreateObjRef(Type) | 创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。(继承自 MarshalByRefObject) | 
| Dispose() | 释放由 Component 使用的所有资源。(继承自 Component) | 
| Dispose(Boolean) | 释放由当前 Timer 使用的所有资源。 | 
| EndInit() | 结束用于窗体或由其他组件使用的 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() | 返回包含 Component 的名称的 String(如果有)。 不应重写此方法。(继承自 Component) | 
事件
| Disposed | 在通过调用 Dispose() 方法释放组件时发生。(继承自 Component) | 
| Elapsed | 达到间隔时发生。 | 
适用于
线程安全性
此类型的任何公共 static 成员都是线程安全的。 但不保证所有实例成员都是线程安全的。