有没有一种方法可以加快/批处理Google日历的读写速度? [英] Is there a way to speed up/batch Google Calendar read/writes?

查看:58
本文介绍了有没有一种方法可以加快/批处理Google日历的读写速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行此项目时,我是Google Apps脚本和学习javascript的新手.在入门代码实验室的过程中,我注意到了

听起来相关的其他相关链接:

  1. 使用高级Google服务(应用脚本资源)li>
  2. Google Developer博客?

解决方案

我相信您的目标如下

  • 您要使用Google Apps脚本的批处理功能删除一个日历中一个月内的所有事件.
  • 您要减少上述过程的过程成本.

为此,这个答案如何?

问题和解决方法:

日历API可以处理批处理请求.批处理请求可以通过一个API调用运行100个请求,并且可以通过异步过程进行处理.由此,我认为可以降低工艺成本.但是,不幸的是,在当前阶段,不能一次使用多个日历ID.当请求包含多个日历ID时,将出现错误无法在同一批处理请求中的不同日历上执行操作..因此,在您的情况下,可以在一个批处理请求中删除一个日历ID中一个月内的所有事件.需要请求日历ID的数量.我想将其作为当前的解决方法.

顺便说一句,作为脚本的修改点,在脚本中,变量 i 在1st for loop和2nd for loop中使用.这样,不会使用 userInfo 的所有值.请注意这一点.

示例脚本:

在运行脚本之前,请在高级Google上启用Calendar API服务.

  function deleteMonth(){今天的var =新的Date();var firstDay = new Date(today.getFullYear(),today.getMonth(),1);var lastDay = new Date(today.getFullYear(),today.getMonth()+ 1,0);var电子表格= SpreadsheetApp.getActiveSpreadsheet();var idSheet =电子表格.getSheetByName('用户信息');var userInfo = getSheetData(idSheet);var DeletedNames =";var个请求= [];//对于批处理请求.对于(i = 0; i< userInfo.length; i ++){var req = [];var calID = userInfo [i] .calID;如果(calID){var calendar = CalendarApp.getCalendarById(calID);var events = calendar.getEvents(firstDay,lastDay);for(j = 0; j< events.length; j ++){DeletedNames + =事件[j] .getTitle()+,";var e = events [j];req.push({方法:删除",端点:`https://www.googleapis.com/calendar/v3/calendars/${calID}/events/${e.getId().replace("@google.com,")}",});}}request.push(req);}//运行批处理请求.request.forEach(req => {const limit = 100;const split = Math.ceil(req.length/limit);const boundary ="xxxxxxxxxx";for(让i = 0; i< split; i ++){const object = {batchPath:"batch/calendar/v3",请求:req.splice(0,limit)};const有效负载= object.requests.reduce((s,e,i)=> s + =内容类型:application/http \ r \ n内容ID:" + i +"\ r \ n \ r \ n"+ e.method +""+ e.endpoint +" \ r \ n内容类型:application/json; charset = utf-8 \ r \ n \ r \ n"+ JSON.stringify(e.requestBody)+"\ r \ n--"+边界+" \ r \ n,"-"+边界+" \ r \ n);;var res = UrlFetchApp.fetch("https://www.googleapis.com/" + object.batchPath,params);console.log(res.getContentText())}})电子表格.toast(已删除的事件:\ n" +删除的名称);} 

注意:

  • 请将此脚本与V8配合使用.

参考文献:

I am new to Google Apps Script and learning javascript as I go about this project. Over the course of the introductory codelabs I noted the best practice to read all the data into an array with one command, perform operations, and then write it with one command.

I understood how to do this working with Google Sheets but how do I achieve this working with Google Calendar? I have come across a few links discussing batching with Google Calendar API and Advanced Google Services but I didn't understand how to make use of the information.

I basically hope to batch edit events instead of accessing Google Calendar repeatedly in a for loop.

function deleteMonth() {

  //  Set Date range to delete 
  var today = new Date();
  var firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
  var lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);

  //  read spreadsheet data and get User Info from ss
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var idSheet = spreadsheet.getSheetByName('User Info');
  //Get users from sheet in array of objects with properties from column header in 
  //'User Info' (name, email, year, calName, calID, early, late)
  var userInfo = getSheetData(idSheet);
  var deletedNames = "";
  for (i = 0; i < userInfo.length; i++) {
    var calID = userInfo[i].calID;
    //    if we have calID proceed to delete events
    if (calID) {
      console.time("get events");
      var calendar = CalendarApp.getCalendarById(calID);
      var events = calendar.getEvents(firstDay, lastDay);
      console.timeEnd("get events");
      //    Delete events and add deleted name to string 
      //    deletedNames     
      for (i = 0; i < events.length; i++) {
        console.time("delete event");
        deletedNames += events[i].getTitle() + ", ";
        events[i].deleteEvent();
        console.timeEnd("delete event");
      }
    }
  }
  spreadsheet.toast("Deleted events: \n" + deletedNames);
}

Time output from console.time():

Other related links which sounded relevant:

  1. Using advanced google services (apps script resource)
  2. Google Developer blog?

解决方案

I believe your goal as follows

  • You want to delete all events in a month for several calendars using the batch process with Google Apps Script.
  • You want to reduce the process cost of above process.

For this, how about this answer?

Issue and workaround:

Calendar API can process with the batch requests. The batch requests can run 100 requests by one API call and can process with the asynchronous process. By this, I think that the process cost can bereduced. But, in the current stage, unfortunately, several calendar IDs cannot be used in one batch. When the requests including several calendar IDs, an error of Cannot perform operations on different calendars in the same batch request. occurs. So in your case, all events in a month in one calendar ID can be deleted in one batch requests. It is required to request the number of calendar IDs. I would like to propose this as the current workaround.

By the way, as the modification point of your scrit, in your script, the variable i is used in 1st for loop and 2nd for loop. By this, all values of userInfo are not used. Please be careful this.

Sample script:

Before you run the script, please enable Calendar API at Advanced Google services.

function deleteMonth() {
  var today = new Date();
  var firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
  var lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var idSheet = spreadsheet.getSheetByName('User Info');
  var userInfo = getSheetData(idSheet);
  var deletedNames = "";
  var requests = []; // For batch requests.
  for (i = 0; i < userInfo.length; i++) {
    var req = [];
    var calID = userInfo[i].calID;
    if (calID) {
      var calendar = CalendarApp.getCalendarById(calID);
      var events = calendar.getEvents(firstDay, lastDay);
      for (j = 0; j < events.length; j++) {
        deletedNames += events[j].getTitle() + ", ";
        var e = events[j];
        req.push({
          method: "DELETE",
          endpoint: `https://www.googleapis.com/calendar/v3/calendars/${calID}/events/${e.getId().replace("@google.com", "")}`,
        });
      }
    }
    requests.push(req);
  }

  // Run batch requests.
  requests.forEach(req => {
    const limit = 100;
    const split = Math.ceil(req.length / limit);
    const boundary = "xxxxxxxxxx";
    for (let i = 0; i < split; i++) {
      const object = {batchPath: "batch/calendar/v3", requests: req.splice(0, limit)};
      const payload = object.requests.reduce((s, e, i) => s += "Content-Type: application/http\r\nContent-ID: " + i + "\r\n\r\n" + e.method + " " + e.endpoint + "\r\nContent-Type: application/json; charset=utf-8\r\n\r\n" + JSON.stringify(e.requestBody) + "\r\n--" + boundary + "\r\n", "--" + boundary + "\r\n");
      const params = {method: "post", contentType: "multipart/mixed; boundary=" + boundary, payload: payload, headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}, muteHttpExceptions: true};
      var res = UrlFetchApp.fetch("https://www.googleapis.com/" + object.batchPath, params);
      console.log(res.getContentText())
    }
  })

  spreadsheet.toast("Deleted events: \n" + deletedNames);
}

Note:

  • Please use this script with V8.

References:

这篇关于有没有一种方法可以加快/批处理Google日历的读写速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆