如何在Google脚本中优化Fileiterator(以避免超时)

时间:2019-07-18 15:17:36

标签: google-apps-script google-drive-api

我要达到Google脚本6分钟超时。该脚本正在运行许多文件夹和子文件夹。我希望有一个(或两个):

  1. 一种优化脚本以更高效/智能地运行数据集/迭代器的方法吗?
  2. 使用getContinuationToken()的方法

任何帮助将不胜感激!

我试图限制脚本运行通过的文件夹/子文件夹的数量。即使在“最小”运行中,它也会超时。仅供参考,我的目标是:

  1. 复制不属于“我”的文件...
  2. 将原始文件(我不拥有)的名称更改为“删除”

代码如下:

FOLDERS = ["0B4FiuEqe8ftGb2lSbjJzakJDNWs"]; /*, "0B4FiuEqe8ftGN2YxZFU5RlhMSDQ", "0B4FiuEqe8ftGN2YxZFU5RlhMSDQ", "1D_1u_KwcLOsBuKyQ7NCsKDd8DB5JwOn6"];*/


function copyNonOwnedFiles() {
var arr = FOLDERS

for (var j = 0; j < arr.length; j++) {

var folderTOP = DriveApp.getFolderById(arr[j]);

var folders = folderTOP.getFolders();
var me = Session.getActiveUser().getEmail();

//RUN #1 = this runs through all of the subfolders
//iterator 1
while (folders.hasNext()) {
var folder = folders.next();

//get all files within these folders 
var files = folder.getFiles();

//iterator 2 
while (files.hasNext()) {
var file = files.next();

var Owner = file.getOwner().getEmail();

if( Owner !== me ){ 
var name = file.getName(); 
file.makeCopy(name);
file.setName('delete'); 
}

}
}

//RUN #2 = this runs through the parent folder
var files2 = folderTOP.getFiles();

//iterator 2 
while (files2.hasNext()) {
var file2 = files2.next();

var Owner = file2.getOwner().getEmail();

if( Owner !== me ){ 
var name2 = file2.getName(); 
file2.makeCopy(name2);
file2.setName('delete'); 
}
}
}
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

此脚本将在具有列出ID的文件夹中找到活动用户拥有的文件,并在无模式对话框中显示它们。该脚本可能需要为多个同时用户使用锁定服务。

var myFiles=[];
var ids=["0B4FiuEqe8ftGb2lSbjJzakJDNWs", "0B4FiuEqe8ftGN2YxZFU5RlhMSDQ", "0B4FiuEqe8ftGN2YxZFU5RlhMSDQ", "1D_1u_KwcLOsBuKyQ7NCsKDd8DB5JwOn6"];
var me='';

function getMyFiles() {
  myFiles=[];
  me=Session.getActiveUser().getEmail();
  for(var i=0;i<ids.length;i++) {
    getFnF(DriveApp.getFolderById(ids[i]));
  }
  var html="<style>th,td{border:1px solid black;}</style><table><tr><th>Item</th><th>Name</th><th>Url</th></tr>";
  for(var i=0;i<myFiles.length;i++) {
    html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td><a href="%s" target="_blank">Link</a></td></tr>',i+1,myFiles[i].name,myFiles[i].url);
  }
  html+='</table><input type="button" value="Close" onClick="google.script.host.close();" />';
  var userInterface=HtmlService.createHtmlOutput(html);
  var title=Utilities.formatString('Files Owned by: %s',me);
  SpreadsheetApp.getUi().showModelessDialog(userInterface, title)
}

function getFnF(folder) {
  var folder= folder || DriveApp.getRootFolder();
  var files=folder.getFiles();
  while(files.hasNext()) {
    var file=files.next();
    if(file.getOwner().getEmail()==me) {
      myFiles.push({name:file.getName(),url:file.getUrl()});
    }
  }
  var subfolders=folder.getFolders() 
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    getFnF(subfolder);
  }
}

答案 1 :(得分:0)

对于有相同问题或类似问题的任何人...我发现使用搜索比文件迭代器更快/更轻松/更少的资源消耗

dataSheetName = "List";

function onOpen(){
 var ui = SpreadsheetApp.getUi();
 ui.createMenu('Custom Menu')
      .addItem('List Files', 'ListFiles')
      .addSeparator()
      .addToUi();
}

function ListFiles() {

   var sheet = SpreadsheetApp.getActive();
   var dataSheet = sheet.getSheetByName(dataSheetName);

   // Clear Sheet
   var lastRow = dataSheet.getLastRow();
  if (lastRow > 0) {
   dataSheet.getRange(2, 1, lastRow, dataSheet.getLastColumn()).clearContent();
  }
  dataSheet.getRange("E2").setValue("Process Started at: " + new Date());
  Logger.log("Start: " + new Date());
//   var row = ['File Name', 'File Id'];
   var row = ['File Name', 'File Id'];
   var data = [];
   data.push(row);
  // Find files modified in the last 24 hours

  var totalDays = 30;

  var today     = new Date();
  var oneDayAgo = new Date(today.getTime() - totalDays * 24 * 60 * 60 * 1000);  
  var startTime = oneDayAgo.toISOString();

  // The magic search expression
  var search = '(trashed = false) and (modifiedDate > "' + startTime + '") and not (title contains \'DELETE\') and not (\'me\' in owners) ';
  // var search = "(mimeType='image/jpeg') and not (title contains 'DELETE') ";
  //  var search = " not ('me' in owners) and not (title contains 'DELETE') ";
  //  var search = " not ('me' in owners) ";
  //var search = 'sharedWithMe';
  // 'me' in owners
  var i = 1;
  var files  = DriveApp.searchFiles(search);
  Logger.log("2: " + new Date());
  dataSheet.getRange("E3").setValue("Search Completed at: " + new Date());

//  while (files.hasNext() && (i < 10000) {
  while (files.hasNext() ) {
     var file = files.next();
    try {
//    data.push([file.getName(),file.getId()]); 
    data.push([file.getName(), file.getId()]); 
    }
    catch (e) {
      Logger.log(file.getName());
    }
 //   i += i;

  }
   // Write data
   var dataRange = dataSheet.getRange(1, 1, data.length, row.length);
   dataRange.setValues(data);
  Logger.log("3: " + new Date());
    dataSheet.getRange("E4").setValue("List Completed at: " + new Date());


}