简体   繁体   English

在固定时间内运行可安装触发器

[英]Run installable trigger for fixed amount of time

How can I run my time based trigger after a certain amount of time.如何在一定时间后运行基于时间的触发器。 Let's say I would like to start the trigger right now and stop after two weeks.假设我想立即启动触发器并在两周后停止。 How can I implement that to the installable trigger?我怎样才能将它实现到可安装的触发器? Is it even possible?甚至可能吗? I'd like to know.我想知道。

ScriptApp.newTrigger("myFunction")
  .timeBased()
  .everyMinutes(10)
  .create();

The easiest method would be to have a function for deleting the trigger and storing the trigger ID in the User Properties.最简单的方法是使用 function 来删除触发器并将触发器 ID 存储在用户属性中。

So you could do something along the lines of this:因此,您可以按照以下方式做一些事情:

function createTrigger() {

  var trigObj = ScriptApp.newTrigger("test")
  .timeBased()
  .everyDays(7)
  .create();

  var props = PropertiesService.getUserProperties();
  var endDate = new Date;
  endDate.setDate(endDate.getDate() + 14);

  props.setProperty('trigId', trigObj.getUniqueId());
  props.setProperty('trigEnd', endDate);
}

function remTrig(){
  var props = PropertiesService.getUserProperties().getProperties();
  var now = new Date;
  var trigs = ScriptApp.getProjectTriggers();
  if (now.getDate() == new Date(props['trigEnd']).getDate()){
    Logger.log('Trigger will be deleted');
    for (var i = 0; i < trigs.length; i++) {
      if (trigs[i].getUniqueId() == props['trigId']){
        Logger.log(`Deleting ${trigs[i].getUniqueId()}`);
        ScriptApp.deleteTrigger(trigs[i]);
      }
    }
  }
  else
    Logger.log(`Trigger to be deleted on ${props['trigEnd']}`);
}

Obviously the trigger check and deletion would have to happen somewhere inside of the function your trigger is calling or you would need a separate daily trigger for the remTrig() function checking if it's time to delete it.显然,触发器检查和删除必须发生在您的触发器正在调用的 function 内部的某个地方,或者您需要为remTrig() function 单独的每日触发器检查是否该删除它。

A few considerations to keep in mind is that this sample is meant for a single trigger per user if you use the first method.需要记住的一些注意事项是,如果您使用第一种方法,则此示例适用于每个用户的单个触发器。 For a daily check if it's time to remove the trigger you'd need to have the function that creates the trigger to create a second one for the deletion check.要每天检查是否需要删除触发器,您需要使用 function 来创建触发器,以便为删除检查创建第二个触发器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM