C# Global.asax.cs 定时任务
定时执行更新Redis缓存操作
protected void Application_Start(object sender, EventArgs e) { Timer timer = new Timer(); timer.Enabled = true; timer.Interval = 3600000; //执行间隔时间,单位为毫秒; 这里实际间隔为1小时 timer.Start(); timer.Elapsed += new System.Timers.ElapsedEventHandler(OrgCacheInterval); } /// <summary> /// 定时检测组织机构缓存是否需要更新 /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void OrgCacheInterval(object source, ElapsedEventArgs e) { SystemService ser = new SystemService(); ser.OrgCacheInterval(); }
/// <summary> /// 组织机构缓存定时更新 /// </summary> public void OrgCacheInterval() { //不存在组织机构缓存或者时间戳时,更新 if (!RedisCacheHelper.Exists("OrgList") || !RedisCacheHelper.Exists("OrgList:Time")) { UpdateAllOrgCache(); } //存在时间戳时判断时间是否一致,不一致时更新 else { //缓存时间戳 string cacheTime = RedisCacheHelper.Get<string>("OrgList:Time"); //数据库更新缓存时间 string modifyTime = OrgDb.GetKeyLastModifyTime("OrgList", ""); //时间戳标记不一致时更新 if (cacheTime != modifyTime) { UpdateAllOrgCache(); } } }
/// <summary> /// 获取键值更新时间 /// </summary> /// <param name="db_key"></param> /// <param name="lang_type"></param> /// <returns></returns> public string GetKeyLastModifyTime(string db_key, string lang_type) { string time = string.Empty; try { string sql = string.Format(@"select * from sys_dbcache_time t where 1=1 and t.db_key='{0}' ", db_key); if (!string.IsNullOrEmpty(lang_type)) { sql += string.Format(@" and t.lang_type='{0}' ", lang_type); } DataTable dt = OdpOracleHelper.Query(sql).Tables[0]; if (dt != null && dt.Rows.Count > 0) { time = Convert.ToDateTime(dt.Rows[0]["op_modify_time"]).ToString("yyyy-MM-dd HH:mm:ss"); } else { string _time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string insertSql = string.Format(@"insert into sys_dbcache_time(db_key,lang_type,op_modify_time)
values('{0}','{1}',to_date('{2}','yyyy-MM-dd HH24:MI:SS'))", db_key, lang_type, _time); OdpOracleHelper.ExecuteSql(insertSql); time = _time; } } catch (Exception ex) { throw ex; } return time; }