应用程序脚本 onedit 触发速度过快,导致代码与自身冲突



我正在尝试在Google电子表格和应用程序脚本中制作一个小程序,该脚本可以抓取有关用户搜索的YouTube视频的视图数据。当用户键入搜索查询时,应从模板工作表复制新工作表,并根据查询进行自定义。我遇到的问题是,当用户快速连续键入多个查询时,脚本会转储模板工作表的多个副本并将它们命名为"模板 1 副本"、"模板 2 副本"等,而每个工作表的名称应该是"KW:"+ 其关联的关键字。我怀疑这是因为该函数复制并重命名工作表,但如果一个函数的两个或多个实例几乎同时尝试此操作,它们将针对同一个工作表,从而导致错误。

这是我尝试过的高潮:

function main(e){
//spreadsheet=SpreadsheetApp.getActiveSpreadsheet() at the top of the function
//keyword=the string the user typed in
//...
while(true){
var random=Math.random().toString();
try{
//assign the template sheet a random name other processes will fail when they try to use it
spreadsheet.getSheetByName('template').setName(random);
//make a copy of the template
spreadsheet.getSheetByName(random).copyTo(spreadsheet);
//give the copy a proper name
spreadsheet.getSheetByName('Copy of '+random).setName("KW: "+keyword);
//reset the name of the template so other processes can use it
spreadsheet.getSheetByName(random).setName('template');
break;
}
//when a process fails, it should wait then try again
catch(e){Utilities.sleep(Math.round(random*250));}
//...
}

Main is 在编辑时设置了一个触发器。上面的代码阻止任何"模板n的副本"工作表出现,但它只是省略了应该生成的大部分工作表。我的猜测是代码在 try 块的第一行遇到错误并循环直到超时。我非常不知所措。我将不胜感激任何帮助,谢谢!

首先尝试复制模板工作表,然后更改新工作表的名称。您的解决方案会遇到错误,因为您正在修改模板工作表,但您应该真正避免这样做。使用此方法,您将永远无法修改模板工作表。

function main(e){
//spreadsheet=SpreadsheetApp.getActiveSpreadsheet() at the top of the function
//keyword=the string the user typed in
//...
while(true){ 
try{
// Select the template sheet
var templateSheet = spreadsheet.getSheetByName("template");
// Set the new sheet name
var sheetName = "KW: "+keyword;
// Copy the template sheet and set name
var newSheet = templateSheet.copyTo(spreadsheet).setName(sheetName);
break;
}
//when a process fails, it should wait then try again
catch(e){Utilities.sleep(Math.round(random*250));}
//...
}
}

当然,我并不完全了解你对你的脚本做了什么,但我确实对你的方法有一些主要的担忧。我认为您不应该为每个查询创建一个新工作表。首先,这将使您的数据非常难以聚合。其次,由于工作表名称必须是唯一的,因此每当有人搜索已经具有现有工作表的内容时,您的函数都会卡在您设置的无限while循环中。

我不知道你在工作表中放置了什么样的数据,但你应该考虑尝试将数据记录在一张工作表中。此外,尽管您的while循环有效,并且在出现错误的情况下最终会因Google的脚本限制而终止,但您确实应该尝试(1)实现更健壮的东西,例如在工作表名称后附加一个数字和(2)正确记录错误。

最新更新