主要通过IHttpModule的Init事件及缓存的过期回调事件来实现定时执行任务。
自定义HttpModule:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TimingTasks.Controllers { public class HttpModule:IHttpModule { public void Init(HttpApplication context) { var tasker = new CacheTimingTasker(); tasker.RegistCacheTimmer(); } public void Dispose() { } } }
CacheTimingTasker:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Hosting; namespace TimingTasks.Controllers { public class CacheTimingTasker { const string LogPath = "~/log/log.txt"; const string CacheKeyName = "TimingTasker";//缓存的名字 const int ExpireTime = 20;//执行周期(秒) private static Cache WebCache = HttpRuntime.Cache; /// <summary> /// 当缓存不存在的时候则注册该缓存 /// </summary> public void RegistCacheTimmer() { if (WebCache[CacheKeyName] != null) return; WebCache.Add(CacheKeyName, '1', null, DateTime.Now.AddSeconds(ExpireTime), Cache.NoSlidingExpiration, CacheItemPriority.High, CacheItemOnRemoved); WriteCacheLog("缓存时钟注册成功"); } /// <summary> /// 缓存过期的回调函数 /// </summary> /// <param name="key">缓存的名字</param> /// <param name="value">缓存的值</param> /// <param name="reason">缓存原因</param> protected void CacheItemOnRemoved(string key, object value, CacheItemRemovedReason reason) { if (key == CacheKeyName) { ExecJob(); RegistCacheTimmer(); } } protected void ExecJob() { //do sth in plan WriteCacheLog("调用计划任务"); } public static void WriteCacheLog(string logInfo) { using (var sw = new StreamWriter(HostingEnvironment.MapPath(LogPath), true, Encoding.UTF8)) { sw.WriteLine(String.Format("{0} {1}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),logInfo)); } } } }
web.config相关设置:
</namespaces> </pages> <httpModules> <add type="TimingTasks.Controllers.HttpModule" name="HttpModule" /> </httpModules> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> </system.web>
测试记录:
参考资料:http://www.goberl.com/archive/item60.aspx
FIN。