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.setDescription()
), nothing fancy. Trying with about 600 events the maximum execution time of 360 seconds is already exceeded.
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);
for (var i = 0; i < events.length; i++) {
events[i].setTitle(events[i].getTitle() + " something");
events[i].setDescription(events[i].getDescription() + " something else");
}
How to process the events in several chunks successively?
Use PropertiesService
to save where you got to so you can continue where you left of on next run.
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.
I hope this is helpful to you!
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.