How to implement a trigger or timer that runs afte

2019-06-10 10:47发布

问题:

At loadtime if the UIapp (= after return app; in doGet() , but before the use can perform mouse or keyboardactions) I have 2 timeconsuming tasks to run. The first task will take 15 to 30 seconds, the second usually takes between 40 and 60 seconds.

In the mean time I want the user to see the UI and be able to enter some data in textboxes and so. So I would like to use idle time and execute the first task using short timeintervals (a few seconds) . This way the user should be able to perform work not requiring task-2 to finish without much delay.

After the first tasks finishes, I want to start task-2 with a somewhat larger timeinterval (10-15 seconds or so).

Reading https://developers.google.com/apps-script/reference/script/clock-trigger-builder , I noticed several remarks about a trigger running within 15 minutes. That's of no use to me. Nevertheless I tried to implement this (see code), but it turns out the code runs once and OCCASIONALLY the trigger runs a second time within a minute or so.

var globalUsedMimeTypes = 'globalUsedMimeTypes';

function getUsedMimeTypes()
{ // Investigate all mimeTypes of existing files
  // As this can be timeconsuming (over 10 seconds for 800 files), this will be done using idle time unless required for searching  
   var Logger = BetterLog.useSpreadsheet('1NYQZqG2z4_2r96L9EFvkbrJJFeb3v3sapPVXjo-Elfo', 'Tree');
   Logger.log('getUsedMimeTypes');  
   var startTime = Date.now();

   deleteTriggerByHandler('getUsedMimeTypes');       // Remove the trigger (if any)

   var delimiter   = ';';
   var maxSeconds  = 2;   // Maximum time allowed for processing each batch
   var waitSeconds = 5;   // Time to wait before the calculation will be resumed

   var currentMimeTypes = '';

   var userProperties = PropertiesService.getUserProperties();
   var continuationToken = userProperties.getProperty('getUsedMimeTypes');
   if (continuationToken == null)
   { // Start new investigation
   Logger.log('continuationToken==null');     
      var files = DriveApp.getFiles();
      var continuationToken = files.getContinuationToken();
      userProperties.setProperty('getUsedMimeTypes', continuationToken);
      userProperties.setProperty(globalUsedMimeTypes, currentMimeTypes);
   }
   else 
   { // Continue from where execution has been interrupted
      var files = DriveApp.continueFileIterator(continuationToken);
      var currentMimeTypes = userProperties.getProperty(globalUsedMimeTypes);
Logger.log('continuation   currentMimeTypes= ' + currentMimeTypes);
   }
   var mimeTypes = currentMimeTypes.split(delimiter);
   var arrMimeTypes = [];
   var numMimeTypes = mimeTypes.length;
   for (var i=0; i<numMimeTypes; i++) arrMimeTypes[mimeTypes[i]] = 0; // Just not 'undefined'

   var maxTime  = maxSeconds * 1000; // Milliseconds allowed per batch --> not tested for now (as numFiles will stop in time)
   var numFiles = 75;                // Maximum number of files to be investigated at a time  
   while ((0 != numFiles--) && files.hasNext())
   {
      var file = files.next();
      var mimeType = file.getMimeType();
      if (arrMimeTypes[mimeType] == undefined)
      { // A new mimeType has been found
Logger.log('found new mimeType = ' + mimeType);
        arrMimeTypes[mimeType] = 0;
        currentMimeTypes = mimeType + delimiter + currentMimeTypes;
        numMimeTypes++;
      }
   }

   continuationToken = files.getContinuationToken();
   if (continuationToken == null)
   { // Finished processing
      currentMimeTypes = currentMimeTypes.substr(0, currentMimeTypes.length - delimiter.length); // Remove delimiter at the end
      userProperties.deleteProperty('getUsedMimeTypes');
   }  
   else
   { // Continue processing  
Logger.log('create new trigger  currentMimeTypes= ' + currentMimeTypes);     
      userProperties.setProperty('getUsedMimeTypes', continuationToken);
      ScriptApp.newTrigger('getUsedMimeTypes').timeBased().after(waitSeconds * 1000).create();
   }  

   userProperties.setProperty(globalUsedMimeTypes, currentMimeTypes); // Store investigated mimeTypes (including delimiter while processing

   var endTime = Date.now();  
   Logger.log('numMimeTypes= ' + numMimeTypes + '   runtime= ' + ((endTime-startTime) / 1000) + ' seconds' + '   finished= ' + (continuationToken == null));  

   return arrMimeTypes;
}  

function deleteTriggerByHandler(nameHandler)
{ // Delete a trigger based on the name of the function it excecutes
   var deleted = false;

   var allTriggers = ScriptApp.getProjectTriggers();

   var numTriggers = allTriggers.length;
   for (var i=0; i < numTriggers; i++)
   {
      if (allTriggers[i].getHandlerFunction() == nameHandler)
      { // Found the trigger we're looking for
         ScriptApp.deleteTrigger(allTriggers[i]);
         deleted = true;
         break;
      }
   }
   return deleted;
}

My questions are:

1) Is it possible to use a trigger for what I intend to do? If not : what can I do to achieve my goal?

2) Do triggers actually have a time period for firing? If so, how much is it and why?

3) As this is the first time I (want to) use a trigger : is my code correct?

4) Should I use idle time (detection by MouseMove and KeyPress)? If so, should I create an achor for the entire panel, or can I use a panel directly?

An example of output:

2014-06-11 23:38:23:273 +0200 049502 INFO Generate memoryTree takes 48.586 seconds
2014-06-11 23:38:23:553 +0200 049782 INFO getUsedMimeTypes
2014-06-11 23:38:24:094 +0200 050323 INFO continuationToken==null
2014-06-11 23:38:25:448 +0200 051678 INFO found new mimeType = application/vnd.google-apps.spreadsheet
2014-06-11 23:38:25:451 +0200 051680 INFO found new mimeType = application/vnd.google-apps.document
2014-06-11 23:38:25:455 +0200 051684 INFO found new mimeType = application/vnd.google-apps.script
2014-06-11 23:38:25:459 +0200 051688 INFO found new mimeType = application/pdf
2014-06-11 23:38:25:499 +0200 051728 INFO create new trigger  currentMimeTypes= application/pdf;application/vnd.google-apps.script;application/vnd.google-apps.document;application/vnd.google-apps.spreadsheet;
2014-06-11 23:38:26:018 +0200 052247 INFO numMimeTypes= 1   runtime= 2.464 seconds   finished= false
2014-06-11 23:38:26:021 +0200 052250 INFO onLoadPageTwoHandler
2014-06-11 23:38:26:023 +0200 052252 INFO onLoadHandlerPageThree
2014-06-11 23:38:42:564 +0200 000875 INFO getUsedMimeTypes
2014-06-11 23:38:43:029 +0200 001340 INFO continuation   currentMimeTypes= application/pdf;application/vnd.google-apps.script;application/vnd.google-apps.document;application/vnd.google-apps.spreadsheet;
2014-06-11 23:38:43:932 +0200 002244 INFO found new mimeType = image/jpeg
2014-06-11 23:38:43:950 +0200 002261 INFO found new mimeType = video/mp4
2014-06-11 23:38:45:039 +0200 003350 INFO found new mimeType = application/vnd.ms-excel
2014-06-11 23:38:45:044 +0200 003355 INFO found new mimeType = application/msword
2014-06-11 23:38:45:070 +0200 003381 INFO found new mimeType = application/vnd.ms-powerpoint
2014-06-11 23:38:45:076 +0200 003387 INFO create new trigger  currentMimeTypes= application/vnd.ms-powerpoint;application/msword;application/vnd.ms-excel;video/mp4;image/jpeg;application/pdf;application/vnd.google-apps.script;application/vnd.google-apps.document;application/vnd.google-apps.spreadsheet;
2014-06-11 23:38:45:417 +0200 003728 INFO numMimeTypes= 9   runtime= 2.849 seconds   finished= false

afterwards no output

回答1:

I solved my problem using addTimer. This allows to split tasks into parts.

Allthough not tested it might even be possible to overcome the 5 minutes limit this way.

function doget()
{
   <usual code>

   var handler = app.createServerHandler('startTask');
   app.addTimer(handler, 3000); // Allow the UI to load and start the tasks afterwards

   return app;
}

function startTask(e)
{ // Perform part 1 of several tasks that take too much time for a responsive UI
   <some actions>

   var handler = app.createServerHandler('partTwo');
   app.addTimer(handler, 1500); // Allow the UI to respond

   return app;
}

function partTwo(e)
{ // Perform part 2 of several tasks that take too much time for a responsive UI
   <actions of part Two ; a continuationToken might be used>

   return app;
}


回答2:

Triggers do not execute within the scope of your app, so you will need to use this workaround: What happens when I "sleep" in GAS ? (execution time limit workaround)