简体   繁体   中英

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:

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. 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...

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.

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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