Google Apps Script Calendar Service: How To Avoid Exceeding Maximum Execution Time?
I need to edit a few hundred or even a few thousand calendar events through Google Apps Script. It is about just minor changes to title (event.setTitle()) and description (event.se
Solution 1:
Answer:
Use PropertiesService
to save where you got to so you can continue where you left of on next run.
Code:
You can use a PropertiesService
key value pair to save the value of the count through events[]
:
functionrenameEvents() {
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = newDate(1850, 0, 1);
var endTime = newDate(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
var sp = PropertiesService.getScriptProperties();
if (!(sp.getProperty("count")) || sp.getProperty("count") == 0) {
var count = 0;
elseif ((sp.getProperty("count") > 0) {
var count = sp.getProperty("count");
}
for (var i = count; i < events.length; i++) {
events[i].setTitle(events[i].getTitle() + " something");
events[i].setDescription(events[i].getDescription() + " something else");
sp.setProperty("count", i)
}
}
It'll make the script a little slower, but each time you run it it'll continue along the calendar events from where the last one stopped.
References:
Solution 2:
I have previously used something similar to the following:
At the start of each loop check that a sufficient buffer time is available to complete the loop.
Update the buffer time whenever a single loop time exceeds it.
Use the PropertiesService
to store both the buffer and the last index.
varcal= CalendarApp.getCalendarById("Calendar Id");
varstartTime=newDate(1850, 0, 1);
varendTime=newDate(2100, 0, 1);
varevents= cal.getEvents(startTime, endTime);
varps= PropertiesService.getScriptProperties();
varstartIndex= ps.getProperty('lastIndex') || 0;
varbuffer= ps.getProperty('buffer') || 100;
varstartTime=newDate();
varmaxTime=1000*60*6; //6 minsfor (vari= startIndex; i < events.length; i++) {
varloopStart=newDate()
if (loopStart - startTime > (maxTime-buffer) ) {
ps.setProperty('lastIndex', i);
break;
}
events[i].setTitle(events[i].getTitle() + " something");
events[i].setDescription(events[i].getDescription() + " something else");
varloopTime=newDate() - loopStart;
if (loopTime > buffer ) buffer = loopTime * 1.5
}
ps.setProperty('buffer',buffer)
Post a Comment for "Google Apps Script Calendar Service: How To Avoid Exceeding Maximum Execution Time?"