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

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

使用

UrlFetchApp.fetch
方法在 Google Drive 中下载 pdf blob 时会导致两种类型的错误:

  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);
}

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

Utilities.sleep(5000)

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

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

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

javascript google-apps-script google-sheets urlfetch
1个回答
7
投票

使用指数退避函数在失败时以指数方式休眠。可以使用

.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);
© www.soinside.com 2019 - 2024. All rights reserved.