简体   繁体   English

Google脚本,按顺序运行函数而不会超过执行时间

[英]Google Script, Run functions in sequence without exceeding execution time

I have a lot of functions that fetch JSON API data from a website, but if I run them in sequence in this way, I get the exceeding execution time error: 我有很多从网站获取JSON API数据的函数,但是如果我以这种方式依次运行它们,则会收到超出执行时间的错误:

function fetchdata () {
    data1();
    data2();
    data3();
    data4();
    ...
}

I can schedule a trigger to run them at 5 minutes one of the other (cause a single one runs in 3 minutes), but I would like to know if there is any other way around. 我可以安排一个触发器在另一个5分钟运行一次(因为一个触发器在3分钟内运行),但是我想知道是否还有其他方法。 Thank you 谢谢

EDIT: Every "data" function is like this one: 编辑:每个“数据”功能是这样的:

function data1() {

  var addresses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Import");
  var baseUrl = 'https://myapiurl';

  var address = addresses.getRange(2, 1, 500).getValues();

  for(var i=0;i<address.length;i++){
    var addrID = address[i][0];
    var url = baseUrl.concat(addrID);
    var responseAPI = UrlFetchApp.fetch(url);
    var json = JSON.parse(responseAPI.getContentText());

    var data = [[json.result]];
    var dataRange = addresses.getRange(i+2, 2).setValue(data);

  }
}

data2 is for rows 502-1001, data3 is for rows 1002-1501, and so on... data2用于502-1001行,data3用于1002-1501行,依此类推...

I just removed the concat because it has performance issues according to MDN but obviously the real problem is the fetch and there's not much we can do about that unless you can get your external api to dump a bigger batch. 我只是删除了concat,因为根据MDN而言,它存在性能问题, 但是显然,真正的问题是获取 ,除非您可以获取外部api来转储更大的批处理,否则我们将无能为力。

You could initiate each function from a webapp and then have it return via withSuccessHandler and then start the next script in the series and daisy chain your way through all of the subfunctions until your done. 您可以从Web应用程序启动每个功能,然后通过withSuccessHandler返回它,然后启动系列中的下一个脚本,并以菊花链方式遍历所有子功能,直到完成。 Each sub function will take it's 3 minutes or so but you only have to worry about keeping each sub function under 6 minutes that way. 每个子功能将花费3分钟左右的时间,但您只需要担心将每个子功能保持在6分钟以内即可。

function data1() 
{
  var addresses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Import");
  var baseUrl = 'https://myapiurl';
  var address = addresses.getRange(2, 1, 500).getValues();
  for(var i=0;i<address.length;i++){
    var responseAPI = UrlFetchApp.fetch(baseUrl + address[i][0]);
    var json = JSON.parse(responseAPI.getContentText());
    var data = [[json.result]];
    var dataRange = addresses.getRange(i+2, 2).setValue(data);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM