为什么谷歌应用程序脚本在编码允许的时间之外运行?

问题描述 投票:0回答:1

下面,该脚本明确只允许周一至周五运行代码。但是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-sheets google-apps-script
1个回答
0
投票

作为另一种方法,使用 Google Apps 脚本库怎么样?我认为管理时间驱动触发器的脚本可能有点困难。因此,我创建了一个 Google Apps 脚本库来管理时间驱动的触发器。 参考

用途:

1.安装 Google Apps 脚本库

您可以在这里查看如何安装TriggerApp。

2.示例脚本

从你的问题来看,如果你想在每个“周一”、“周二”、“周三”、“周四”和“周五”的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);
}

3.奔跑吧

在这种情况下,请运行上述函数

sample
。这样,就安装了下一个触发器。该脚本的流程如下。

  1. sample
    在“2024-04-17 00:00:00”运行时,触发器将安装到“2024-04-17 17:00:00”。 <--- Wednesday
  2. sample
    在“2024-04-17 17:00:00”运行时,触发器将安装到“2024-04-18 17:00:00”。 <--- Thursday
  3. sample
    在“2024-04-18 17:00:00”运行时,触发器将安装到“2024-04-19 17:00:00”。 <--- Friday
  4. sample
    在“2024-04-19 17:00:00”运行时,触发器将安装到“2024-04-22 17:00:00”。 <--- Monday
  5. sample
    在“2024-04-22 17:00:00”运行时,触发器将安装到“2024-04-23 17:00:00”。 <--- Tuesday

这个循环继续运行。

注:

  • 在此脚本中,使用了 2 个触发器。从
    I just added 5 weekly timers, choosing Mon, Tues, etc.
    开始,我觉得这个方法或许可以减少触发次数。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.