问题描述
我有一个 google 表格脚本设置,可以检查多个 url 的 http 服务器状态。
function getStatusCode(url){
var options = {
'muteHttpExceptions': true,'followRedirects': false
};
var url_trimmed = url.trim();
var response = UrlFetchApp.fetch(url_trimmed,options);
return response.getResponseCode();
}
然后在我的电子表格中我有:
___________ A ___________| __________ B __________ |
www.mysite.com/mypage1 __| "=getStatusCode(A1)"
www.mysite.com/mypage2 __| "=getStatusCode(A2)"
等等...
现在,只要我打开工作表(而且有很多),脚本就会在所有单元格上运行。有什么办法可以安排它,以便它按照我选择的时间表/限制在少数单元格上执行脚本?最理想的选择是告诉它在单元格 A1 上运行脚本,然后在单元格 A2 等上运行它之前暂停指定的时间。
解决方法
您可以使用 Cache Service 最大限度地减少对外部端点的调用次数。您可能还应该让您的自定义函数与数组一起工作,以便它可以通过一次调用(如 =getStatusCode(A1:A)
)来填充整列。有关详细信息,请参阅 Google 的 custom function optimization 页面。
答案:
您可以使用分钟触发器每分钟运行一个查询,使用 PropertiesService
来存储您浏览工作表的距离。
更多信息:
PropertiesService
是一个类,它允许您将信息存储在脚本中,以便在每次运行时都可以访问它。这意味着您可以跨运行保留信息/变量,即使在脚本完成执行之后也是如此。
想法是这样的:
- 创建一个属性存储来保存脚本运行的最后一行
- 在每次运行时,检查属性商店。如果保存了最后一行,则在下一行运行脚本,并将新的最后一行保存到属性存储。
- 如果当前行是空的,假设我们已经到达工作表的末尾并删除了属性存储。
- 如果没有属性存储,则重新从工作表的开头开始
- 每分钟运行一次脚本,所以每次检索状态码都会错开
代码示例:
// Copyright 2021 Google LLC.
// SPDX-License-Identifier: Apache-2.0
// Define your sheet so it can be accessed from all functions
const ss = SpreadsheetApp.getActiveSpreadsheet()
// Don't forget to change your sheet name:
const sheet = ss.getSheetByName("Sheet1")
// This is the function to run on minute trigger
function onMinuteTrigger() {
// Define the property service and check if there is a last row saved
const sp = PropertiesService.getScriptProperties()
let row = sp.getProperty("last")
// if there was no last row,set the 'row' variable to 0
if (!row) row = 0
// add 1 to row so the script runs on the next row,not the last
row++
// call the status code function
const statusCode = getStatusCode(row)
// if the statusCode is null then the row was blank;
// so delete the property store and return
if (statusCode == null) {
sp.deleteProperty("last")
return
}
// if the script has got this far there was a returned status code
// save the status code to the sheet and save the new last row
// to the property store
sheet.getRange(row,2).setValue(statusCode)
sp.setProperty("last",row)
}
连同对您的 statusCode()
方法稍加修改的版本:
// modified statusCode function from your question
// pass to it the row to update
function getStatusCode(row) {
const options = {
'muteHttpExceptions': true,'followRedirects': false
}
// manually get the url from the passed row variable
const url_trimmed = sheet.getRange(row,1).getValue().trim()
// if url_trimmed is blank then the row is empty,return null
if (url_trimmed.length == 0) return null
// fetch the URL and return the response code
const response = UrlFetchApp.fetch(url_trimmed,options)
return response.getResponseCode()
}
希望对你有帮助!