[英]Schedule a task refreshing HttpContext.Cache every day at a certain time
我有一個運行MVC 3 c#的網站從web服務中提取記錄。 隨着它從Web服務獲取的數據集變得越來越大,我正在尋找一種方法,在沒有當前緩存的情況下,第一個用戶不會在沒有當前緩存的情況下觸發創建緩存,而是按照每日計划(像cron工作,計划任務或其他)。
我該怎么做? 我是否需要某種類似Quartz.net的觸發器庫? (我寧願使用更簡單的解決方案)
我現在在控制器中擁有的是:
private List<DataSummary> GetSummaries()
{
//get summaries from cache if available
List<DataSummary> summaries = (List<DataSummary>)HttpContext.Cache["SummariesCache"];
if (summaries == null)
{
//cache empty, retrieve values
summaries = _webservice.GetSummaries();
//cache it
HttpContext.Cache.Add("SummariesCache", summaries, null, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
return summaries;
}
編輯
使用CacheItemRemovedCallback
會導致超時錯誤
這是一個hacky解決方案,但您始終可以在運行可執行文件的服務器上創建計划任務。 此可執行文件會訪問您網站上的特定URL,而后者又會按照您上面概述的方式填充緩存。 要點擊可執行文件中的URL,您需要以下內容:
var req = (HttpWebRequest)WebRequest.Create(URL);
req.Timeout = 30000;
req.KeepAlive = false;
req.Method = "GET";
var res = (HttpWebResponse)req.GetResponse();
if (res.StatusCode == HttpStatusCode.OK){
// Your cache should be refreshed
}
創建計划任務也非常簡單 - 只需確保在對您創建的exe具有執行權限的用戶帳戶中運行它,並且不要求用戶登錄以啟動任務。
編輯:添加了在Windows Server 2008上設置計划任務的指南
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.