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[]
:
function renameEvents() {
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = new Date(1850, 0, 1);
var endTime = new Date(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
var sp = PropertiesService.getScriptProperties();
if (!(sp.getProperty("count")) || sp.getProperty("count") == 0) {
var count = 0;
else if ((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.
var cal = CalendarApp.getCalendarById("Calendar Id");
var startTime = new Date(1850, 0, 1);
var endTime = new Date(2100, 0, 1);
var events = cal.getEvents(startTime, endTime);
var ps = PropertiesService.getScriptProperties();
var startIndex = ps.getProperty('lastIndex') || 0;
var buffer = ps.getProperty('buffer') || 100;
var startTime = new Date();
var maxTime = 1000*60*6; //6 mins
for (var i = startIndex; i < events.length; i++) {
var loopStart = new Date()
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");
var loopTime = new Date() - 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?"