Google脚本超出了最大执行时间

时间:2016-05-11 17:07:54

标签: google-apps-script

通过google工作表文档中的jdbc连接到sql server数据库。该表有大约30k个奇数记录并且命中超过最大执行时间"错误。有没有办法提高性能或解决6分钟的执行时间。



function myFunction() {
  var conn = Jdbc.getConnection("jdbc:sqlserver://dbURL", "username", "password");
  var stmt = conn.createStatement();
  stmt.setMaxRows(3000);
  var start = new Date();
  var rs = stmt.executeQuery('SELECT * FROM dbo.myTable');
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var cell = doc.getRange('a1');
  var row = 0;
  var data = [];
  while (rs.next()) {
    var rowData = [];
    for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
      rowData[col] = (rs.getString(col + 1));
    }
    data[row] = rowData;
    row++;
  }
  rs.close();
  stmt.close();
  conn.close();
  var end = new Date();
  Logger.log('Time elapsed: ' + (end.getTime() - start.getTime()));
}
&#13;
&#13;
&#13;

谢谢。

修改代码以使用连续批处理库,即使我没有得到超出执行时间错误看起来像是进入无限循环并且没有将一条记录写入工作表。

&#13;
&#13;
var FUNCTION_NAME = "test";
var EMAIL_RECIPIENT = "";

function test() {
  
  ContinuousBatchLibrary.startOrResumeContinousExecutionInstance(FUNCTION_NAME)
  
  var conn = Jdbc.getConnection("jdbc:sqlserver://HOST:PORT/DBNAME","user","password");
  var stmt = conn.createStatement();
  stmt.setMaxRows(100);
  var rs = stmt.executeQuery('SELECT * FROM myTable');
  var SS;
  var Sheet;
  var SheetRange;
  
  // OPEN EXISTING SPREADSHEET
  SS = SpreadsheetApp.openById(SpreadsheetApp.getActiveSpreadsheet().getId());
  
  // SET SPREADSHEET ACTIVE
  SpreadsheetApp.setActiveSpreadsheet(SS);  
  Sheet = SpreadsheetApp.setActiveSheet(SS.getSheetByName(SpreadsheetApp.getActiveSpreadsheet().getSheetName()));  
  
  // GET NUMBER OF COLUMNS
  var ColCount = rs.getMetaData().getColumnCount(); 
  
  // SET COLUMN HEADERS
    for (var col = 1; col <= ColCount; col++) {
      GSheet.getRange(1, col).setValue(rs.getMetaData().getColumnName(col));
    }
  
  // SET RANGE TO FIRST ROW AND BOLD
  GSheetRange = GSheet.getRange(1,1,1,GSheet.getLastColumn());  
  GSheetRange.setFontWeight("bold");  

  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var cell = doc.getRange('a2');
  var row = 0;
  var data = [];
  var i = ContinuousBatchLibrary.getBatchKey(FUNCTION_NAME) || 0;

  for (; i < row.length; i++) {
  while (rs.next()) {
    var rowData = [];
    for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
      rowData[col] = (rs.getString(col + 1));
    }
    data[row] = rowData;
    row++;
  }
    if (ContinuousBatchLibrary.isTimeRunningOut(FUNCTION_NAME)) {
        ContinuousBatchLibrary.setBatchKey(FUNCTION_NAME, i)
        break;
      }
    }
  
  rs.close();
  stmt.close();
  conn.close();

    if (i === row.length) {
    ContinuousBatchLibrary.endContinuousExecutionInstance(FUNCTION_NAME, EMAIL_RECIPIENT, "task complete")
  } 
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这个answer可能仍然是6分钟计时器的最佳工作。

累积触发器运行时间限制是一天一小时,因此如果您在超时之前获得的数据超过10%,那么您也会遇到这种情况。