UrlFetchApp.fetch 引发流量大 | 超时错误

Avi*_*vin 3 javascript google-sheets urlfetch google-apps-script

使用方法在谷歌驱动器中下载 pdf blob 时UrlFetchApp.fetch会导致两种类型的错误:

  1. </div></div>This file might be unavailable right now due to heavy traffic. <a href="">Try again</a>.</div> [Written in downloaded PDF]

  2. 异常:超时

代码片段:

function downloadasPDF(optSSId, optSheetId)
{
 var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();

 var preURL=ss.getUrl() //ss is an spreadsheet reference
 var url = preURL.replace(/edit.*/,'');
 var folder = DriveApp.getFolderById(FolderID);
 // Get array of all sheets in spreadsheet
 var sheets = ss.getSheets();

 for (var i=0; i<sheets.length; i++) {
   //Sheet length is 100+

   Utilities.sleep("5000")
   var sheet = sheets[i];

   // If provided a optSheetId, only save it.
   if (optSheetId && optSheetId !== sheet.getSheetId()) continue; 

   //additional parameters for exporting the sheet as a pdf
   var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf
     + '&gid=' + sheet.getSheetId()   //the sheet's Id
     + '&gridlines=false'  // hide gridlines

   var options = {
     headers: {
       'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken()
     },
     muteHttpExceptions: true,
   }
   var response = UrlFetchApp.fetch(url + url_ext, options);
   var blob = response.getBlob().setName(spreadsheet.getName() + ' - ' + sheet.getName() + '.pdf');
   folder.createFile(blob);
}
Run Code Online (Sandbox Code Playgroud)

为了解决上述问题,我正在使用:

Utilities.sleep(5000)
Run Code Online (Sandbox Code Playgroud)

但仍有一些文件导致上述错误 1。

问:除了睡眠之外,我们还有其他更好的方法来处理上述两种情况吗?

注意:我使用的是 G Suite Enterprise,要下载的工作表数量约为 100-150 个,每个工作表填充 240 个单元格,其余单元格为空。

The*_*ter 9

使用指数退避函数在失败时以指数方式休眠。可以通过以下方式检查失败.getResponseCode()

const response = (function exponentialBackoff(i) {
  Utilities.sleep(Math.pow(2, i) * 1000);
  const data = UrlFetchApp.fetch(url + url_ext, options);
  if (data.getResponseCode() !== 200) return exponentialBackoff(++i);
  else return data;
})(0);
Run Code Online (Sandbox Code Playgroud)

  • @AbinLakhanpal 删除你原来的 5000 睡眠并只使用这个。 (2认同)
  • @AbinLakhanpal - 另外,您始终可以扩展实用程序以使其在多次重试后退出。您只需在确认响应代码为“!== 200”并提前退出后检查“i === maxNumberOfRetries”是否 (2认同)