4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【GAS】毎日実行するトリガーに終了期限を設定したい

Last updated at Posted at 2020-11-04

概要

一定期間は毎日実行したいけど、ある期日を過ぎたら実行したくない。

けど、トリガーの設定には終了期限がない・・・。

なのでスクリプト側に記述して解決してみた。

方法

if文で終了期限の前かを判定して実行するのがシンプルかと思ったけど、そうすると期限以降もトリガーが残ってしまい、見えないところで実行され続けるのが気持ち悪い^^;

期限以降のどこかのタイミングでトリガーを削除してやれば良いとは言え、せっかく便利に自動化したんだから最後までほったらかしにしたい!

と言うわけで、終了期日が来たらトリガーを削除するようなスクリプトを作る。

コード

function delTrigger() {

  const today = new Date(); 
  const limit = new Date('2039/12/31');
  
  if(today>limit){
    
    const triggers = ScriptApp.getProjectTriggers();
    for(const trigger of triggers){
    
      if(trigger.getHandlerFunction() == '関数名'){
  
        ScriptApp.deleteTrigger(trigger);
      
      }
    }
  }
}

本日が期日を超えていたなら、triggersに全てのトリガーを格納して、for文で総ざらい。目当ての関数名がセットされたトリガーがあれば削除!

todayには実行時の日時が入り、limitには指定日の0時0分が入るので、実行したいスクリプトの最後にdelTrigger();を差し込んであげればOK^^)b

limit日程の実行を最後にトリガーが消滅する。

おしまい

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?