Tuesday, December 6, 2011

The Cloud with Google Apps Script

  Sometimes you want to cache data in your script. For example, there’s a RSS feed you want to use and a UiApp that you’ve built to view and process the feed. Up until now, each operation to work on the feed would require re-fetching the feed, which can get slow. Enter the newly launched CacheService which will allow for caching resources between script executions. Like the recently announced LockService, there are two kinds of caches: a public cache that is per-script, and a private cache which is per-user, per-script. The private cache should be used to store user-specific data, while the public cache is used to store strings that should be accessible no matter who calls the script. So for our example feed viewer/processor, you’d already have a function to retrieve and process the feed. In order to use the CacheService, you’d wrap it like this:
function getFeed() {
  var cache = CacheService.getPublicCache();
  var value = cache.get(“my rss feed”);
  if (value == null) {
    // code to fetch the contents of the feed and store it in value
    // here (assumes value is a string) 

    // cache will be good for around 3600 seconds (1 hour)
    cache.put(“my rss feed”, value, 3600);
  return value;
The cache doesn’t guarantee that you won’t have to fetch it again sooner, but will make a best effort to retain it for that long, and expire it quickly after the time passes. Now you can call getFeed() often and it won’t re-fetch the feed from the remote site on each script execution, resulting in improved performance.

No comments:

Post a Comment

Share This: