首页 > 解决方案 > 添加多个联系人超出时间

问题描述

我正在尝试像这样向谷歌插入/更新多个联系人(1000+):

(循环中:)

      if (contact == null) {
        contact = ContactsApp.createContact(first_name, last_name, email);
        group.addContact(contact);
      } else {
        contact.setFullName(first_name+' '+last_name);
        contact.setGivenName(first_name);
        contact.setFamilyName(last_name);
      }

它工作正常,但是在大约 1 分钟后(添加了 100-130 个联系人)脚本停止:

错误超过最大执行时间

有没有解决的办法?

标签: google-apps-script

解决方案


问题:

Apps 脚本的执行时间限制为 6 或 30 分钟,具体取决于您的帐户。您很可能会达到此限制。

解决方法:

为避免这种情况,您可以通过设置基于时间的触发器将要执行的操作拆分为不同的执行,该触发器将在前一个执行完成后触发每个后续执行。我猜你的函数有一个循环,所以你可以按照以下步骤操作:

  • 找出脚本在达到时间限制(可能是 6 分钟)之前可以经过多少次迭代。每次执行在停止之前都必须经过这么多的迭代。
  • 在函数结束时创建以下基于时间的触发器:after(durationMilliseconds)。多亏了这一点,您可以在指定的毫秒数之后运行您指定的任何函数。每次执行后,将创建一个触发器来触发下一个触发器。
  • 让你的循环成为一个for循环。因为您必须拆分循环,所以您必须将循环计数器(让我们调用它i)存储在某处(您可以在每次执行结束时使用PropertiesService,或将其写入电子表格)并在下一次开始时检索它,这样每个在连续执行中,脚本都知道在哪里恢复循环。例如,如果您不知道如何存储和检索脚本属性,请参阅此答案。

示例代码(检查内联注释):

function createContacts() {
  // Whatever your code outside the loop is
  var i_old = // Retrieve i stored in previous execution (from PropertiesService? Spreadsheet?) (should be 0 if first execution)
  var n_int = 100 // Number of iterations that can be done in a single execution without reaching time limit (change accordingly)
  var total = 1000 || yourVariable.length // Total number of iterations (change accordingly)
  // Loop starts at previous i store until it reaches the specified number of iterations for one execution or reaches the total number:
  for(var i = i_old; i <= i_old + n_int && i <= total; i++) {
    // Whatever your code inside the loop is
  }
  // Store i somewhere (PropertiesService? Spreadsheet?)
  if (i <= total) { // Create trigger if i hasn't reach the total number of iteration
    ScriptApp.newTrigger("createContacts")
    .timeBased()
    .after(1000 * 60) // This fires the function 1 minute after the current execution ends. Change this time according to your preferences
    .create();  
  }
}

笔记:

  • 请注意,每天只能创建1,000 或 2,000 个联系人(取决于帐户类型)。

参考:


推荐阅读