Have you ever opened a page for one of your websites and it lags for a while before it finally shows a page but then all of your following requests are quick? If you were to Google the problem you’d find that often it ends up having to do with IIS meeting an idle time limit and shuts down your site.
Keep me Alive
private static void _SetupRefreshJob() { //remove a previous job Action remove = HttpContext.Current.Cache["Refresh"] as Action; if (remove is Action) { HttpContext.Current.Cache.Remove("Refresh"); remove.EndInvoke(null); } //get the worker Action work = () => { while (true) { Thread.Sleep(60000); //TODO: Refresh Code (Explained in a moment) } }; work.BeginInvoke(null, null); //add this job to the cache HttpContext.Current.Cache.Add( "Refresh", work, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, (s, o, r) => { _SetupRefreshJob(); } ); }
If we place this code in the Global.asax and call it when Application_Start() is raised, we can basically start a job that keeps our website alive. You could just as easily use a Thread to host the refresh method but for this example we simply used an Action delegate.
Once our application starts the refresh job is also started and is saved to the cache. In this example we’re using 60 seconds, but you can change this to be as often as you like.
So How Can We Keep It Fresh?
So how about an example of some code we can use? Here is a simple example that could keep our website alive. Replace the //TODO: in the example above with something like the following.
WebClient refresh = new WebClient(); try { refresh.UploadString("http://www.website.com/", string.Empty); } catch (Exception ex) { //snip... } finally { refresh.Dispose(); }
This snippet uses a WebClient to actually make an HTTP call to our website, thus keeping the site alive! We could do any number of things from this code like updating local data or get information from external resource. This can be used to keep our site alive and our content refreshed, even if we’re using a Hosted Environment!
It is worth nothing that might not actually need to do an HTTP call back to your website. It is possible that using any method will keep your website from being killed off (but I haven’t tested it yet so let me know what happens if you try it). This example, however, has been tested and works quite well with my provider.
You need to be careful that you don’t call a page with any Analytics attached, otherwise you’ll get false reading in your logs.