LibrarySites.Banner

Schedule Expiration for Output Cache Entries with the Sitecore ASP.NET CMS

The Sitecore Cache Expiration Setting thread on the Sitecore Developer Network (SDN) forums prompted me to write this blog post that describes how you can set an expiration time frame for each presentation control using the Sitecore ASP.NET CMS. I have to thank Christopher Giddings for pointing me towards the relevant information in the original forum thread Sitecore Caching for SSL + non-SSL sublayout.

Sitecore maintains a number of caches, including internal data caches, output caches for each managed web site, and separate media caches. For more information about caching, see the Cache Configuration Reference on SDN. For more information about caching presentation components, see the Presentation Component Reference on SDN.

By default, publishing evicts dependant cache entries from Sitecore's caches. You might need to evict cache entries under other conditions, for example data from an external source. You could implement a custom solution to manage caching of this data, or use the Sitecore.Tasks.HtmlCacheClearAgent agent to schedule cache clearing (which would clear an excessive amount of cache), or you could use the Sitecore output cache, and use the CacheTimeout property of the Sitecore.Web.UI.WebControl class. For more information about using agents to schedule processes, see my blog post All About Sitecore Scheduling Agents and Tasks.

If the CacheTimeout property of the control is set for a presentation control when adding its output to an output cache, Sitecore calculates manages an absolute expiration date based on that TimeSpan and the system time. I don't know exactly what evicts entries from the cache after reaching this limit, but your control will render and cache again after that time passes.

To set the CacheTimeout property programatically, for a web control, you could cache for 30 seconds with code something like this:

this.CacheTimeout = new TimeSpan(0, 0, 30);

Sublayouts are a little more tricky, because the sublayout isn't a web control that inherits from Sitecore.Web.UI.WebControl, but a separate class that operates as the child of a Sitecore.Web.UI.WebControls.Sublayout object used to invoke the sublayout, which does inherit from Sitecore.Web.UI.WebControl:

Sitecore.Web.UI.WebControl parent = this.Parent as Sitecore.Web.UI.WebControl;

if (parent != null)
{
  parent.CacheTimeout = new TimeSpan(0, 0, 30);
}

To set the CacheTimeout property statically (from the .aspx or .ascx file), set the CacheTimeout property to a value using a template such as "<Days>.<Hours>:<Minutes>:<Seconds>", for example 1.00:00:00 for one day. You can use this technique for web controls, sublayouts and XSL files. For example:

<sc:XslFile runat="server" CacheTimeout="1.00:00:00" Path="/xsl/..." />