[英]Schedule a task refreshing HttpContext.Cache every day at a certain time
I have an MVC 3 c# website running which pulls records from a webservice. 我有一个运行MVC 3 c#的网站从web服务中提取记录。 As the dataset it gets from the webservice becomes bigger and bigger, I'm searching for a way that creating the cache of it isn't triggered by the first user to visit the site while there is no current cache, but on a daily schedule (like a cron job, scheduled task or something).
随着它从Web服务获取的数据集变得越来越大,我正在寻找一种方法,在没有当前缓存的情况下,第一个用户不会在没有当前缓存的情况下触发创建缓存,而是按照每日计划(像cron工作,计划任务或其他)。
How should I do this? 我该怎么做? Do I need some sort of trigger library like Quartz.net ?
我是否需要某种类似Quartz.net的触发器库? (I'd rather use a simpler solution)
(我宁愿使用更简单的解决方案)
What I have in my controller now is: 我现在在控制器中拥有的是:
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;
}
Edit 编辑
using CacheItemRemovedCallback
causes time-out errors 使用
CacheItemRemovedCallback
会导致超时错误
This is a bit of a hacky solution but you could always create a scheduled task on the server which runs an executable. 这是一个hacky解决方案,但您始终可以在运行可执行文件的服务器上创建计划任务。 This executable hits a particular URL on your website, which in turn populates the cache exactly as you've outlined above.
此可执行文件会访问您网站上的特定URL,而后者又会按照您上面概述的方式填充缓存。 To hit the URL in the executable you'd need something along these lines:
要点击可执行文件中的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
}
Creating a scheduled task is pretty simple as well - just make sure you run it in a user account that has execute permissions on the exe you create and don't require the user to be logged on for the task to start. 创建计划任务也非常简单 - 只需确保在对您创建的exe具有执行权限的用户帐户中运行它,并且不要求用户登录以启动任务。
Edit: Added a guide to setting up a scheduled task on Windows Server 2008 编辑:添加了在Windows Server 2008上设置计划任务的指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.