asp.net Cache定时器

跟据Cache的过期回调写的asp.net web定时器.

/// <summary> /// 缓存定时器事件委托 /// created by lihui 20100702 /// </summary> public delegate void CacheTimerEventsHandler(object sender, CacheTimerEventsArgs e); /// <summary> /// 缓存定时器事件参数 /// created by lihui 20100702 /// </summary> public sealed class CacheTimerEventsArgs : EventArgs { public CacheTimer Timer { get; set; } #region = Constructor = public CacheTimerEventsArgs(CacheTimer timer) { Timer = timer; } #endregion } /// <summary> /// 缓存定时器 /// created by lihui 20100702 /// </summary> public class CacheTimer : Component { /// <summary> /// Cache关键字 /// </summary> public string Key { get; set; } /// <summary> /// Cache值 /// </summary> public object Value { get; set; } /// <summary> /// 频率(间隔以秒为单位) /// </summary> public int IntervalSeconds { get; set; } /// <summary> /// 开始时间,小时 /// </summary> public int BeginHour { get; set; } /// <summary> /// 开始时间,分钟 /// </summary> public int BeginMinute { get; set; } /// <summary> /// 下一次执行时间 /// </summary> public DateTime NextExecuteTime { get; set; } /// <summary> /// 是否是第一次执行 /// </summary> private bool _isFirstTime = true; /// <summary> /// 获取当前Cache /// </summary> public static Cache CurrentCache { get { var context = HttpContext.Current; return context != null ? context.Cache : HttpRuntime.Cache; } } #region =Event= private static readonly object _executing = new object(); /// <summary> /// 定时器按频率所执行的事件 /// </summary> public event CacheTimerEventsHandler Executing { add { this.Events.AddHandler(_executing, value); } remove { this.Events.RemoveHandler(_executing, value); } } #endregion /// <summary> /// 构造 /// </summary> /// <param name="key">Cache关键字</param> /// <param name="value">Cache值</param> /// <param name="intervalSeconds">频率(间隔以秒为单位)</param> /// <param name="beginHour">开始时间,小时</param> /// <param name="beginMinute">开始时间,分钟</param> public CacheTimer(string key, object value, int intervalSeconds,int beginHour,int beginMinute) { Key = key; Value = value; BeginHour = beginHour; BeginMinute = beginMinute; IntervalSeconds = intervalSeconds; } /// <summary> /// 获取缓存定时器 /// </summary> /// <param name="key">Cache关键字</param> /// <returns>缓存定时器</returns> public static CacheTimer GetTimer(string key) { if (CurrentCache[key] == null) return null; return (CacheTimer)CurrentCache[key]; } /// <summary> /// 当缓存不存在的时候则注册该缓存 /// </summary> public void RegisterCacheTimer() { if (CurrentCache[Key] != null) return; //计算下次运行时间 NextExecuteTime = BuildNextExecuteTime(); //去掉“秒”位 //NextExecuteTime = DateTime.Now.AddSeconds(NextExecuteTime.Second*-1); CurrentCache.Add(Key, this, null, NextExecuteTime, Cache.NoSlidingExpiration, CacheItemPriority.High, CacheOnRemoved); } /// <summary> /// 计算Cache过期时间,即事件开始运行时间 /// </summary> /// <returns>下一次执行时间</returns> private DateTime BuildNextExecuteTime() { if (!_isFirstTime) return DateTime.Now.AddSeconds(IntervalSeconds); _isFirstTime = false; var beginSeconds = BeginHour*60*60 + BeginMinute*60; var nowSeconds = DateTime.Now.Hour*60*60 + DateTime.Now.Minute*60; if (beginSeconds <= nowSeconds) { while (beginSeconds <= nowSeconds) { beginSeconds += IntervalSeconds; } } else { beginSeconds += IntervalSeconds; } var todayZero = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); return todayZero.AddSeconds(beginSeconds); //if (nowSeconds == beginSeconds) // return IntervalSeconds; //if (nowSeconds > beginSeconds) //{ // while (beginSeconds <= nowSeconds) // { // beginSeconds += IntervalSeconds; // } // return beginSeconds - nowSeconds; //} //return beginSeconds - nowSeconds; } /// <summary> /// 停止定时器,删除缓存 /// </summary> public void StopCacheTimer() { if (CurrentCache[Key] == null) return; ((CacheTimer)CurrentCache[Key]).Value = null; RemoveExecutingHandler(); CurrentCache.Remove(Key); _isFirstTime = true; } /// <summary> /// 缓存过期的回调函数 /// </summary> /// <param name="key">缓存的名字</param> /// <param name="value">缓存的值</param> /// <param name="reason">缓存销毁原因</param> protected void CacheOnRemoved(string key, object value, CacheItemRemovedReason reason) { if (!key.Equals(Key)) { return; } if (reason != CacheItemRemovedReason.Expired) return; if (((CacheTimer)value).Value == null) return; OnExecuting(new CacheTimerEventsArgs(this)); RegisterCacheTimer(); } /// <summary> /// 定时器在频率中执行触发的事件 /// </summary> /// <param name="e">定时器事件</param> protected void OnExecuting(CacheTimerEventsArgs e) { var handler = (CacheTimerEventsHandler)this.Events[_executing]; if (handler != null) { handler(this, e); } } /// <summary> /// 移除事件绑定 /// </summary> protected void RemoveExecutingHandler() { var handler = (CacheTimerEventsHandler)this.Events[_executing]; if (handler != null) { this.Executing -= handler; } } }

代码中都有注释,下面列个例子:

var timer = CacheTimer.GetTimer("key") ?? new CacheTimer("key", "Cache定时器", 60, 11, 50); timer.Executing += new CacheTimerEventsHandler(TimerExecuting); timer.RegisterCacheTimer(); void TimerExecuting(object sender, CacheTimerEventsArgs e) { //FileHelper.WriteText(@"D:/lihui.txt", e.Timer.Key + "|" + e.Timer.Value + "|" + DateTime.Now.ToString() + "/n", true); //这里是定时调度的操作,上面是我自己的测试 }

其中vartimer=CacheTimer.GetTimer( "key" )?? new CacheTimer( "key" , "Cache定时器" ,60,11,50);

参数“ 60,11,50”说明是在11点50分开始,每隔60秒运行一次


停止定时器:

var timer = CacheTimer.GetTimer("key"); if (timer != null) timer.StopCacheTimer();

查看定时器状态:

var timer = CacheTimer.GetTimer("key"); if (timer != null) { //说明正在运行 //下次运行时间:timer.NextExecuteTime } else { //说明没有运行 }

每个key对应一个定时器,需要注意的是:当IIS进程销毁,程序重新编译,重启IIS等操作都会删除ASP.NET程序所用到的内存,因此,定时也就停止工作,可以在Application_Start(即程序第一次运行)中开启所有定时器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值