1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GAS 指定した時刻に定期実行する

Posted at

概要

GASの定期実行では、決まった時刻に定期実行設定することができず、何時~何時の間で実行する、といったような曖昧な設定しかできない。
スクリプトで設定すれば、毎日何時何分に実行させる、といった設定ができる。

トリガー作成/削除 スクリプト

// 定数
const functionName1 = 'function1';
const functionName2 = 'function2';
const deleteTriggerFunctionName = [functionName1, functionName2];


/**
 * 指定時間に実行させるトリガーを作成
 * 
 * ※この関数を定期実行設定しておく
 */
function mainTriggerFunction(){
  let runTime = new Date();

  // functionName1を毎日17:00に実行する
  runTime.setHours(17);
  runTime.setMinutes(00);
  setTrigger(functionName1, runTime);

  // functionName1を毎日17:30に実行する
  runTime.setHours(17);
  runTime.setMinutes(30);
  setTrigger(functionName2, runTime);
}

/**
 * 実際にトリガーを作成する
 * @param functionName 
 * @param date 
 */
function setTrigger(functionName, date){
  ScriptApp.newTrigger(functionName).timeBased.at(date).create();
}

/**
 * 指定したトリガーを削除する
 * (実行し終わったトリガーを溜めておきたくないため)
 * 
 * ※この関数を定期実行設定しておく
 */
function deleteTrigger(){
  const allTriggers = ScriptApp.getProjectTriggers();
  for (let i = 0; i <= allTriggers.length; i++){
    if (deleteTriggerFunctionName.includes(allTriggers[i].getHandlerFunction())){
      ScriptApp.deleteTrigger(allTriggers[i]);
    }
  }
}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?