0
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?

More than 1 year has passed since last update.

Googleフォームを毎日回答受付・終了する(その2)

Posted at

1 目的

先日、Googleフォームを毎日回答受付開始・終了するというのを書きました。これを実行して放置していると使い終わったトリガーが毎日溜まっていきますが、トリガー数には1スクリプトあたり20という制限があるので適当に削除する必要があります。そこで、トリガーを設定する前に古いトリガーを削除するよう、書いてみました。

2 スクリプト

script.gs
//開始後一定時間後(openHoursで指定)に終了する関数
function startAndClose1() {
  const formId = 'フォームID';
  const myform = FormApp.openById(formId);
  myform.setAcceptingResponses(true);
  const openHours = 1;
  const mytrigger = 'closeForm1';
  delTrigger(mytrigger); //古いトリガーの削除
  ScriptApp.newTrigger(mytrigger)
    .timeBased()
    .after(openHours * 60 * 60 * 1000)
    .create();
}

//終了時間を指定(closeDateTimeで指定)し、開始後、指定時間に終了する関数
function startAndClose2(){
  const formId = 'フォームID';
  const myform = FormApp.openById(formId);
  myform.setAcceptingResponses(true);
  const currentDate = new Date();
  const closeDateTime = new Date(
    currentDate.getFullYear(),
    currentDate.getMonth(),
    currentDate.getDate(),
    8, 30, 0, 0
  );
  const mytrigger = 'closeForm1';
  delTrigger(mytrigger); //古いトリガーを削除
  const triggerTime = closeDateTime.getTime() - currentDate.getTime();
  if (triggerTime > 0) {
    ScriptApp.newTrigger(mytrigger)
      .timeBased()
      .after(triggerTime)
      .create();
    Logger.log('回答受付を終了するトリガーが設定されました。');
  } else {
    Logger.log('指定の日時が過去のため、トリガーを設定できません。');
  }
}

function closeForm1() {
  const formId = 'フォームID';
  const myform = FormApp.openById(formId);
  myform.setAcceptingResponses(false);
}

//トリガーを削除する
function delTrigger(mytrigger2) {
  const mytriggers = ScriptApp.getProjectTriggers();
  for (let i = 0; i < mytriggers.length; i++) {
    if (mytriggers[i].getHandlerFunction() === mytrigger2) {
    ScriptApp.deleteTrigger(mytriggers[i]);
    }
  }
}

終わりの部分に、トリガーを削除する関数delTriggerを追加しました。この関数はstartAndClose1とstartAndClose2から使われ、削除するトリガー名を引数で受け取ります。ScriptApp.getProjectTriggers()でトリガーの一覧を取得し、該当するトリガー名(関数名)のものを削除します。

3 参考

0
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
0
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?