.NET System.Timers.Timer的原理和使用(开发定时执行程序)
概述(来自MSDN)
Timer 组件是基于服务器的计时器,它使您能够指定在应用程序中引发 Elapsed 事件的周期性间隔。然后可以操控此事件以提供定期处理。例如,假设您有一台关键性服务器,必须每周 7 天、每天 24 小时都保持运行。可以创建一个使用 Timer 的服务,以定期检查服务器并确保系统开启并在运行。如果系统不响应,则该服务可以尝试重新启动服务器或通知管理员。
基于服务器的 Timer 是为在多线程环境中用于辅助线程而设计的。服务器计时器可以在线程间移动来处理引发的 Elapsed 事件,这样就可以比 Windows 计时器更精确地按时引发事件。
基于 Interval 属性的值,Timer 组件引发 Elapsed 事件。可以处理该事件以执行所需的处理。例如,假设您有一个联机销售应用程序,它不断向数据库发送销售订单。编译发货指令的服务分批处理订单,而不是分别处理每个订单。可以使用 Timer 每 30 分钟启动一次批处理。
注意
当 AutoReset设置为false时,Timer只在第一个Interval过后引发一次Elapsed事件。若要保持以Interval时间间隔引发 Elapsed 事件,请将AutoReset设置为true。
Elapsed事件在ThreadPool线程上引发。如果Elapsed事件的处理时间比Interval长,在另一个hreadPool线程上将会再次引发此事件。因此,事件处理程序应当是可重入的。
注意
在一个线程调用 Stop 方法或将 Enabled 属性设置为 false 的同时,可在另一个线程上运行事件处理方法。这可能导致在计时器停止之后引发 Elapsed 事件。Stop 方法的示例代码演示了一种避免此争用条件的方法。
如果和用户界面元素(如窗体或控件)一起使用 Timer,请将包含有 Timer 的窗体或控件赋值给SynchronizingObject 属性,以便将此事件封送到用户界面线程中。 Timer 在运行时是不可见的。
几点说明
private System.Timers.Timer _TestTimerEvent= new Timer();
1、默认的周期是0.1秒执行一次;
2、AutoReset的初始值为true.
3、它的timer机制和System.Threading.Timer 原理是一样的。
我们来看它的实现代码.(.net framework 提供的).
//------------------------------------------------------------------------------
// <copyright file="Timer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Timers {
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.ComponentModel;
using System.ComponentModel.Design;
using System;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
/// <devdoc>
/// <para>Handles recurring events in an application.</para>
/// </devdoc>
[
DefaultProperty("Interval"),
DefaultEvent("Elapsed"),
HostProtection(Synchronization=true, ExternalThreading=true)
]
public class Timer : Component, ISupportInitialize {
private double interval;
private bool enabled;
private bool initializing;
private bool delayedEnable;
private ElapsedEventHandler onIntervalElapsed;
private bool autoReset;
private ISynchronizeInvoke synchronizingObject;
private bool disposed;
private System.Threading.Timer timer;
private TimerCallback callback;
private Object cookie;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.</para>
/// </devdoc>
public Timer()
: base() {
interval = 100;
enabled = false;
autoReset = true;
initializing = false;
delayedEnable = false;
callback = new TimerCallback(this.MyTimerCallback);
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </para>
/// </devdoc>
public Timer(double interval)
: this() {
if (interval <= 0)
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "interval", interval));
int i = (int)Math.Ceiling(interval);
if( i < 0) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "interval", interval));
}
this.interval = interval;
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed,
/// when Enabled is set to true.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerAutoReset), DefaultValue(true)]
public bool AutoReset {
get {
return this.autoReset;
}
set {
if (DesignMode)
this.autoReset = value;
else if (this.autoReset != value) {
this.autoReset = value;
if( timer != null) {
UpdateTimer();
}
}
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able
/// to raise events at a defined interval.</para>
/// </devdoc>
//[....] - The default value by design is false, don't change it.
[Category("Behavior"), TimersDescription(SR.TimerEnabled), DefaultValue(false)]
public bool Enabled {
get {
return this.enabled;
}
set {
if (DesignMode) {
this.delayedEnable = value;
this.enabled = value;
}
else if (initializing)
this.delayedEnable = value;
else if (enabled != value) {
if (!value) {
if( timer != null) {
cookie = null;
timer.Dispose();
timer = null;
}
enabled = value;
}
else {
enabled = value;
if( timer == null) {
if (disposed) {
throw new ObjectDisposedException(GetType().Name);
}
int i = (int)Math.Ceiling(interval);
cookie = new Object();
timer = new System.Threading.Timer(callback, cookie, i, autoReset? i:Timeout.Infinite);
}
else {

浙公网安备 33010602011771号