我想在 google sheet 脚本中为每个循环添加 2 mint 延迟以发送电子邮件,但 setTimeout 和 sleep 不起作用

问题描述

我希望在一次循环更改后有 2 分钟的延迟。意味着我想在发送电子邮件添加一些延迟。 完整的代码链接是(https://github.com/googleworkspace/solutions/blob/master/mail-merge/src/Code.js)

   obj.forEach(function(row,rowIdx){
   sleep(1200000);
    // only send emails is email_sent cell is blank and not hidden by filter
    if (row[EMAIL_SENT_COL] == ''){
      try {
        const msgObj = fillInTemplateFromObject_(emailTemplate.message,row);

    // @see https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,Object)
    // if you need to send emails with unicode/emoji characters change GmailApp for MailApp
    // Uncomment advanced parameters as needed (see docs for limitations)
    GmailApp.sendEmail(row[RECIPIENT_COL],msgObj.subject,msgObj.text,{
      htmlBody: msgObj.html,// bcc: '[email protected]',// cc: '[email protected]',// from: '[email protected]',// name: 'name of the sender',// replyTo: '[email protected]',// noreply: true,// if the email should be sent from a generic no-reply email address (not available to gmail.com users)
      attachments: emailTemplate.attachments,inlineImages: emailTemplate.inlineImages
    });
    // modify cell to record email sent date
    out.push([new Date()]);
  } catch(e) {
    // modify cell to record error
    out.push([e.message]);
  }
} else {
  out.push([row[EMAIL_SENT_COL]]);
}
});

解决方法

解决方案:

您可以使用 Installable Trigger 每分钟运行一次 sendEmails()。这可以在选择菜单项时创建:

编辑: 由于不允许 everyMinute(2),因此一种解决方法是让函数每分钟执行一次。由于有一个列会在发送电子邮件后更新,因此在第一次执行时,它会将列标记为“要发送”,在第二次执行时,它将发送电子邮件。


function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('Mail Merge')
      .addItem('Send Emails','createTrigger')
      .addToUi();
}

function createTrigger() {
  ScriptApp.newTrigger("sendEmails")
    .timeBased()
    .everyMinutes(1)
    .create();
}

然后用一个简单的 for 循环替换 forEach(),这样一旦第一封电子邮件被标记为发送或发送,它就可以跳出循环。

  // loop through the rows of data and break once one email is sent
  for (i = 0; i < obj.length; i++) {
    var row = obj[i];
    // Mark emails with "To Send" if email_sent cell is blank. Only send emails if email_sent cell is "To Send" and not hidden by filter
    if (row[EMAIL_SENT_COL] == ''){
      out.push(['To Send']);
      break;
    } else if (row[EMAIL_SENT_COL] == 'To Send'){
      try {
        const msgObj = fillInTemplateFromObject_(emailTemplate.message,row);

        // @see https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,Object)
        // if you need to send emails with unicode/emoji characters change GmailApp for MailApp
        // Uncomment advanced parameters as needed (see docs for limitations)
        GmailApp.sendEmail(row[RECIPIENT_COL],msgObj.subject,msgObj.text,{
          htmlBody: msgObj.html,// bcc: '[email protected]',// cc: '[email protected]',// from: '[email protected]',// name: 'name of the sender',// replyTo: '[email protected]',// noReply: true,// if the email should be sent from a generic no-reply email address (not available to gmail.com users)
          attachments: emailTemplate.attachments,inlineImages: emailTemplate.inlineImages
        });
        // modify cell to record email sent date
        out.push([new Date()]);
      } catch(e) {
        // modify cell to record error
        out.push([e.message]);
      }
      break;
    } else {
      out.push([row[EMAIL_SENT_COL]]);
    }
  }

一旦处理完所有的行,删除触发器:

  // updating the sheet with new data
  sheet.getRange(2,emailSentColIdx+1,out.length).setValues(out);

  if (out.length == obj.length) {
    var triggers = ScriptApp.getProjectTriggers();
    for (var j = 0; j < triggers.length; j++) {
    ScriptApp.deleteTrigger(triggers[j]);
    }
  }