28
30

More than 3 years have passed since last update.

【GAS】GASで値を保存して次の実行時でも利用する

Last updated at Posted at 2019-11-03

概要

値を保存する手段としてSpreadsheet, Propertie, Cache などの方法がありますが、今回はCacheについてです。
以下ぞれぞれの特徴です。

CacheはリファレンスにもありますがRSSの更新確認のためなどに使うには便利そうです。
前回の実行時間の確認やデータの引き継ぎなどの一時的なデータは文字通りキャッシュを利用したほうが良さそうです。

Cache Serviceサンプルプログラム

データは保存時に文字列に変換されてしまいます。ラップしてJSONで変換するほうが使いやすそうです。

function makeCache() {
  const cache = CacheService.getScriptCache();
  return {
    get: function(key) {
      return JSON.parse(cache.get(key));
    },
    put: function(key, value, sec) {
      //リファレンスよりcache.putの3つ目の引数は省略可。
      //デフォルトでは10分間(600秒)保存される。最大値は6時間(21600秒)
      cache.put(key, JSON.stringify(value), (sec === undefined) ? 600 : sec);
      return value;
    }
  };
}

function test3() {
  const cache = makeCache();

  Logger.log(cache.put('array',[1,2]))
  Logger.log(typeof cache.get('array'))

  Logger.log(cache.put('number',256))
  Logger.log(typeof cache.get('number'))

  Logger.log(cache.put('string','test'))
  Logger.log(typeof cache.get('string'))

  Logger.log(cache.put('date', new Date()))
  Logger.log(typeof cache.get('date'))

  Logger.log(cache.put('object',{a:[1,2], b:1, c:'test'}))
  Logger.log(typeof cache.get('object'))
}

/*以下 ログ
[19-11-03 14:41:56:238 JST] [1.0, 2.0]
[19-11-03 14:41:56:278 JST] object
[19-11-03 14:41:56:340 JST] 256.0
[19-11-03 14:41:56:381 JST] number
[19-11-03 14:41:56:428 JST] test
[19-11-03 14:41:56:456 JST] string
[19-11-03 14:41:56:511 JST] Sun Nov 03 14:41:56 GMT+09:00 2019
[19-11-03 14:41:56:560 JST] string
[19-11-03 14:41:56:623 JST] {a=[1.0, 2.0], b=1.0, c=test}
[19-11-03 14:41:56:637 JST] object
*/
28
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
30