下面,该脚本明确只允许周一至周五运行代码。但是tt可以在版本历史中看到,它一直在周六和周日运行,并且确实在周六和周日更新了sheet内的数据。
function copyDataToHistorical() {
// Check if today is a weekday (Monday to Friday)
var today = new Date();
var dayOfWeek = today.getDay(); // 0 is Sunday, 1 is Monday, ..., 6 is Saturday
// Check if it's a weekday (Monday to Friday)
if (dayOfWeek >= 1 && dayOfWeek <= 5) {
// Get the active spreadsheet and sheets
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var todaySheet = spreadsheet.getSheetByName("TodaysData");
var historicalSheet = spreadsheet.getSheetByName("HistoricalData");
// Get the data range from TodaysData
var dataRange = todaySheet.getRange("A4:O16");
// Get the values from the range
var values = dataRange.getValues();
// Find the last unused row in HistoricalData
var lastRow = historicalSheet.getLastRow();
var lastColumn = historicalSheet.getLastColumn();
var lastRowValues = historicalSheet.getRange(lastRow, 1, 1, lastColumn).getValues()[0];
// Check if the last row is empty
var isEmpty = lastRowValues.every(function(value) {
return value === '';
});
// If the last row is not empty, find the next empty row
if (!isEmpty) {
lastRow = historicalSheet.getLastRow() + 1;
}
// Copy the values to HistoricalData
historicalSheet.getRange(lastRow, 1, values. Length, values[0].length).setValues(values);
} else {
Logger.log("Today is not a weekday.");
}
}
作为另一种方法,使用 Google Apps 脚本库怎么样?我认为管理时间驱动触发器的脚本可能有点困难。因此,我创建了一个 Google Apps 脚本库来管理时间驱动的触发器。 参考
您可以在这里查看如何安装TriggerApp。
从你的问题来看,如果你想在每个“周一”、“周二”、“周三”、“周四”和“周五”的17:00运行函数
copyDataToHistorical
,示例脚本如下。在这种情况下,您的函数copyDataToHistorical
不需要修改。
function sample(e) {
const obj = [
{
ownFunctionName: "sample",
functionName: "copyDataToHistorical",
everyWeek: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
atTimes: ["17:00:00"],
},
];
const res = TriggerApp.setEventObject(e).installTriggers(obj, console.log);
console.log(res);
}
在这种情况下,请运行上述函数
sample
。这样,就安装了下一个触发器。该脚本的流程如下。
sample
在“2024-04-17 00:00:00”运行时,触发器将安装到“2024-04-17 17:00:00”。 <--- Wednesdaysample
在“2024-04-17 17:00:00”运行时,触发器将安装到“2024-04-18 17:00:00”。 <--- Thursdaysample
在“2024-04-18 17:00:00”运行时,触发器将安装到“2024-04-19 17:00:00”。 <--- Fridaysample
在“2024-04-19 17:00:00”运行时,触发器将安装到“2024-04-22 17:00:00”。 <--- Mondaysample
在“2024-04-22 17:00:00”运行时,触发器将安装到“2024-04-23 17:00:00”。 <--- Tuesday这个循环继续运行。
I just added 5 weekly timers, choosing Mon, Tues, etc.
开始,我觉得这个方法或许可以减少触发次数。