通过Timer可以定期调用指定的代码,C#中的Timer可以每隔几秒或者几分钟定期指定一个指定的函数。如果我们需要定时监控重要程序的状态或者变量状态都非常有用。Timer被定义在System.Timers命名空间内。
举例:
下面这个C#范例是定义了一个静态类,这意味着它不能有实例成员或字段。它包括System.Timers命名空间,它定义了一个定时执行的函数,每隔3秒钟向List列表中添加一个当前日期。
using System;
using System.Collections.Generic;
using System.Timers;
public static class TimerExample // In App_Code folder
{
static Timer _timer; // From System.Timers
static List<DateTime> _l; // Stores timer results
public static List<DateTime> DateList // Gets the results
{
get
{
if (_l == null) // Lazily initialize the timer
{
Start(); // Start the timer
}
return _l; // Return the list of dates
}
}
static void Start()
{
_l = new List<DateTime>(); // Allocate the list
_timer = new Timer(3000); // Set up the timer for 3 seconds
//
// Type "_timer.Elapsed += " and press tab twice.
//
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true; // Enable it
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_l.Add(DateTime.Now); // Add date on each timer event
}
}
注意:这个C#类没有输出,必须通过外部调用
下面是一个通过.aspx调用timer的实例
using System;
using System.Web;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpResponse r = Response; // Get reference to Response
foreach (DateTime d in TimerExample.DateList) // Get the timer results
{
r.Write(d); // Write the DateTime
r.Write("<br/>"); // Write a line break tag
}
}
}
这段C#代码调用上面定义的TimerExample类,在浏览器中输出时间,如果你不断的刷新网页,会不断的有新的项目加入
