I have an MVC 3 c# website running which pulls records from a webservice. 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).
How should I do this? Do I need some sort of trigger library like 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
This is a bit of a hacky solution but you could always create a scheduled task on the server which runs an executable. This executable hits a particular URL on your website, which in turn populates the cache exactly as you've outlined above. To hit the URL in the executable you'd need something along these lines:
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.
Edit: Added a guide to setting up a scheduled task on Windows Server 2008
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With