在asp.net中使用定時器,破寶之前已有blog寫過《在 asp.net 中使用計時器(timer)》,這里主要針對asp.net forums來說一下其具體實現。
在asp.net forums中,對定時器有如下應用:
1. 更新論壇統計信息
2. 定時索引指定條數的帖子
3. 定時群發隊列中的郵件
forums中對定時器的調用是放在自定義httpmodule的init方法中(如果您沒有使用httpmodule,也可以在globals.aspx中的application_onstart 中調用定時器)。
// 定時器
static timer statstimer;
static timer emailtimer;
// 定時間隔
private long emailinterval = forumconfiguration.getconfig().threadintervalemail * 60000;
private long statsinterval = forumconfiguration.getconfig().threadintervalstats * 60000;
public string modulename {
get { return "forumshttpmodule"; }
}
// *********************************************************************
// forumshttpmodule
//
/**//// <summary>
/// initializes the httpmodule and performs the wireup of all application
/// events.
/// </summary>
/// <param name="application">application the module is being run for</param>
public void init(httpapplication application) {
// wire-up application events
//
// 略去其他代碼
forumconfiguration forumconfig = forumconfiguration.getconfig();
// 如果使用定時器并且定時器還沒初始化
if( forumconfig != null
&& forumconfig.isbackgroundthreadingdisabled == false ) {
if (emailtimer == null)
// 新建定時器
// 新建一個timercallback委托,具體要執行的方法在scheduledworkcallbackemailinterval中
emailtimer = new timer(new timercallback(scheduledworkcallbackemailinterval), application.context, emailinterval, emailinterval);
if( forumconfig.isindexingdisabled == false
&& statstimer == null ) {
statstimer = new timer(new timercallback(scheduledworkcallbackstatsinterval), application.context, statsinterval, statsinterval);
}
}
}
/**//// <summary>
/// 釋放定時器
/// </summary>
public void dispose() {
statstimer = null;
emailtimer = null;
}
timer callbacks
#region timer callbacks
/**//// <summary>
/// 定時發送隊列中待發送的郵件
/// </summary>
private void scheduledworkcallbackemailinterval (object sender) {
try {
// 當處理郵件時暫停定時器
emailtimer.change( system.threading.timeout.infinite, emailinterval );
// 發送隊列中的郵件
//
emails.sendqueuedemails( (httpcontext) sender);
// 更新匿名用戶
//
users.updateanonymoususers( (httpcontext) sender);
}
catch( exception e ) {
forumexception fe = new forumexception( forumexceptiontype.emailunabletosend, "scheduled worker thread failed.", e );
fe.log();
}
finally {
// 重新啟動定時器
emailtimer.change( emailinterval, emailinterval );
}
}
/**//// <summary>
/// 定時索引帖子和定時更新論壇統計信息
/// </summary>
private void scheduledworkcallbackstatsinterval(object sender) {
try {
// 休眠定時器
statstimer.change( system.threading.timeout.infinite, statsinterval );
// 每次索引100篇帖子
//
search.indexposts( (httpcontext) sender, 100);
// 更新論壇統計信息
sitestatistics.loadsitestatistics( (httpcontext) sender, true, 1 );
}
catch( exception e ) {
forumexception fe = new forumexception( forumexceptiontype.unknownerror, "failure performing scheduled statistics maintenance.", e );
fe.log();
}
finally {
// 喚醒定時器
statstimer.change( statsinterval, statsinterval);
}
}
#endregion
其實稍加改進就可以應用到我們自己的項目中,例如前不久剛做一個項目,因為數據量過于龐大,每次從數據庫取非常慢,然后改成使用定時器,每隔12小時將最新的數據列表生成靜態的文本。
新聞熱點
疑難解答
圖片精選