Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Utilities.sleep() function

What is the exact use of Utilities.sleep() function? Should we use it between function calls or API calls?

I use the Utilities.sleep(1000) in-between function calls, is it right? Will it slow down the execution time?

like image 673
balajiboss Avatar asked Jun 21 '12 16:06

balajiboss


2 Answers

Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.

Here is an example :

function delsheets(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
  for (pa=numbofsheet-1;pa>0;--pa){ 
    ss.setActiveSheet(ss.getSheets()[pa]);
    var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
    Utilities.sleep(200);// pause in the loop for 200 milliseconds
  }
  ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
like image 79
Serge insas Avatar answered Oct 22 '22 03:10

Serge insas


Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}
like image 12
juuulek Avatar answered Oct 22 '22 03:10

juuulek