在WEB應用程序里執行定時器(Timer),運行於服務器端
我們可以在 ASP.NET 中使用計時器(Timer)完成一些定時動作。這一點可能會對我們的一些 Web 程序有益。
如定時生成表態列表、在線人數、最新主題貼,等等。。。很方便
.NET Framework v1.1
1
using System.Timers;
2
3
4
protected void Application_Start(Object sender, EventArgs e)
5
{
6
System.Timers.Timer timer = new System.Timers.Timer(1000);
7
8
//AutoReset 屬性為 true 時,每隔指定時間循環一次;
9
//如果為 false,則只執行一次。
10
timer.AutoReset = true;
11
timer.Enabled = true;
12
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.setTime);
13
14
Application.Lock();
15
Application["time"] = DateTime.Now.ToString();
16
Application.UnLock();
17
}
18
19
public void setTime(Object sender, ElapsedEventArgs e)
20
{
21
Application.Lock();
22
Application["time"] = DateTime.Now.ToString();
23
Application.UnLock();
24
}
using System.Timers;
2
3
4
protected void Application_Start(Object sender, EventArgs e)
5
{6
System.Timers.Timer timer = new System.Timers.Timer(1000);7

8
//AutoReset 屬性為 true 時,每隔指定時間循環一次;9
//如果為 false,則只執行一次。10
timer.AutoReset = true;11
timer.Enabled = true;12
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.setTime);13
14
Application.Lock();15
Application["time"] = DateTime.Now.ToString();16
Application.UnLock();17
}18

19
public void setTime(Object sender, ElapsedEventArgs e)20
{21
Application.Lock();22
Application["time"] = DateTime.Now.ToString();23
Application.UnLock();24
}
例子中只是很簡單的更新 Appcation["time"] 值而已,還可以實現更多更好的功能。
