我有一个名为alertnotice(to, message, body)
的函数,它将在用户onClick()
事件上执行。该函数将执行sendEmail(to, message, body)
以根据计算的触发器发送电子邮件,如变量triggerDay
,如下所示:
function alertnotice(to, subject, body, dueDate, notifyBeforeDay) {//start of this class
function sendEmail(to, subject, body){
try {
MailApp.sendEmail({
to: to,
subject: subject,
htmlBody: body
});
} catch(e) {
console.error(JSON.stringify(e));
}
}
//check if there is an existing trigger for this process
var existingTrigger = PropertiesService.getScriptProperties().getProperty("sendEmailTrigger");
//set the renewal notice day
var triggerDay = (dueDate - notifyBeforeDay) / (1000*60*60*24);
//if the trigger already exists, inform user about it
if(existingTrigger) {
return "Alert notice had been sent";
} else { // if the trigger does not exists, continue to set the trigger to send alert notice
//runs the script every day at 1am on the time zone specified
var newTrigger = ScriptApp.newTrigger('sendEmail')
.timeBased()
.atTime(triggerDay)
.create();
var triggerId = newTrigger.getUniqueId();
if(triggerId) {
PropertiesService.getScriptProperties().setProperty("autoExportTrigger", triggerId);
return "Alert notice send successfully!";
} else {
return "Failed to send alert notice. Try again please";
}
}
}//end of this class
例如,如果dueDate为 30/07/2018 和notifyBeforeDay = 30
,则该函数应在截止日期前30天发送电子邮件。我试图实现这一目标,但不确定我的算法是否有效。任何人都可以就此提出建议吗?
答案 0 :(得分:0)
这个实现对我来说很脆弱。我宁愿单手触发以避免任何可能的重复电子邮件并确保至少一个。像这样的Smth:
// I am server script, trigger me on schedule (for instance nightly)
function sendAlerts() {
var query = app.models.Customers.newQuery();
// query only for non-notified customers with upcoming due date
query.filters.NorificationAttempts._lessThan = ATTEMPTS_THRESHOLD;
query.filters.Notified._equals = false;
query.filters.DueDate._lessThan = <dueDate>;
var customers = query.run();
customers.forEach(function(customer) {
var success = sendNotification(customer);
if (success) {
customer.Notified = true;
} else {
customer.NorificationAttempts++;
}
// performance trade off in favor of consistency
app.saveRecords([customer]);
});
}
此类脚本的触发器可以由应用管理员安装,您可以在People Skills模板中找到类似的实现。