Google Apps 脚本在定时触发器上执行脚本比手动(按需)执行脚本需要更长的时间

问题描述 投票:0回答:0

我在 Google Apps 中编写了一个小脚本来处理存储在 Google 云端硬盘中的约 200 多个文件。处理过程基本上包括将它们全部复制到一个主文件中,也存储在我的 Google 云端硬盘中,并执行一些基本的格式化。

我注意到,当脚本按需执行时(我将其设置为手动运行),每批处理 20 个文件需要 不到 大约 10 秒,因此成功完成的时间很大程度上低于每个执行集 360 秒的限制通过谷歌。

但是,当它从时间触发器执行时,设置为一小时的间隔,它总是超过 360 秒的限制来处理大约 100 到 180 个文件(这取决于一天中的时间?),因此无法成功完成.

在这两种情况下,脚本应该花费相同的时间来完成。谷歌显然为脚本执行分配了不同的优先级,具体取决于它是“按需”运行还是基于时间触发器。

我读到有一些解决方法可以解决 360 秒的时间限制,但据我所知,我的脚本非常能够在比这更短的时间内运行。谁能帮我解决这个问题吗?

编辑 2023-08-02 添加更多信息

我使用通过互联网搜索找到的代码示例将脚本编写为独立脚本,相关部分如下所示。

makeDoc
函数采用两个参数,一个 Google Drive 文件 ID 和一个包含要处理的文件列表(以及其他内容)的对象,打开主文件,将其他文件复制到其中,然后处理所有文件一一:

function makeDoc(mainDocID, rowsIDs) {
  var mainDoc = DocumentApp.openById(mainDocID);
  var body = mainDoc.getBody();

  // This sequence of clear, save and close, and reopen is required to avoid 'ScriptError: Too many changes applied before saving document'.
  // https://stackoverflow.com/questions/50875601/how-do-you-re-open-the-active-document-after-calling-saveandclose
  body.clear(); // clear the whole document
  mainDoc.saveAndClose(); // save and close the document
  mainDoc = DocumentApp.openById(mainDocID); // reopen the document
  body = mainDoc.getBody();

  // extract data from object
  var header = rowsIDs.header;
  var values = rowsIDs.rows; // TOC list
  var docIDs = rowsIDs.ids; // atoms list

  // start writing the file
  body.appendParagraph(header).setBold(true);
  body.appendParagraph('').setBold(false);
//  body.appendTable(values);

  // append atoms from database
  for (var i = 0; i < values.length; i++) {
//    body.appendPageBreak();
    var otherBody = DocumentApp.openById(docIDs[i]).getActiveSection();
    var totalElements = otherBody.getNumChildren();
    var isHeader = true;

    if (i%20 == 19) { // progress indicator
      Logger.log('Processados '+Utilities.formatString('%03d', i+1)+' cânticos');
    }

    for (var j = 0; j < totalElements; ++j) {
      var element = otherBody.getChild(j).copy();
      
      switch (element.getType()) {
        case DocumentApp.ElementType.PARAGRAPH :
          if (isHeader) {
            element.insertText(0, Utilities.formatString('%03d', i+1)+'. ').setBold(true);
            isHeader = false;
          }
          body.appendParagraph(element);
          break;
        case DocumentApp.ElementType.TABLE :
          body.appendTable(element);
          break;
        case DocumentApp.ElementType.LIST_ITEM :
          body.appendListItem(element).setGlyphType(DocumentApp.GlyphType.NUMBER);
          break;
        default:
          throw new Error('Unknown element type: ' + element.getType())
      }
    }
  }
  mainDoc.saveAndClose(); // close the file
}

以下是通过时间触发器启动脚本时的执行日志的两个示例:

这是手动启动脚本时成功执行的示例(出于隐私原因,我从日志中删除了倒数第二行):

google-apps-script eventtrigger execution-time ondemand
© www.soinside.com 2019 - 2024. All rights reserved.