如何在Google Apps Script中每隔数秒调用一次自定义函数?
Google Sheets 定时刷新随机冷笑话实现方案
Google Apps Script 运行在服务端环境,不支持浏览器端的setInterval/setTimeout定时器API,官方提供的时间驱动触发器是替代实现定时任务的正式方案,以下是可直接落地的实现步骤:
步骤1:修改LOL自定义函数
无参的自定义函数会被Google Sheets默认缓存结果,只有参数变化时才会重新计算,因此我们新增一个控制参数用来触发刷新:
function LOL(control) { // 可自行替换成你想要的任意笑话内容 let messageList = [ "Where do dads keep their jokes? In a dad-abase!", "When does a joke become a dad joke? When it becomes a-parent!", "Two men walk into a bar. You'd think the second one would've noticed!", "Does your face hurt? 'Cause it's killing me!" ] const random = Math.floor(Math.random() * messageList.length); return messageList[random] }
步骤2:新增控制触发器执行的辅助函数
选择表格内任意一个闲置单元格作为控制位(示例用Sheet1!A1,可自行替换),每次运行该函数就修改控制位的数值,触发所有引用该控制位的LOL函数重算:
function updateControlCell() { // 替换为你选择的闲置控制单元格位置 const controlCell = SpreadsheetApp.getActiveSpreadsheet().getRange("Sheet1!A1"); const currentValue = controlCell.getValue() || 0; controlCell.setValue(currentValue + 1); }
步骤3:创建1分钟周期的时间触发器
- 打开脚本编辑器左侧的「触发器」面板(闹钟形状图标)
- 点击右下角「添加触发器」,按以下规则配置:
- 选择要运行的函数:
updateControlCell - 选择事件源:
时间驱动 - 选择触发器类型:
分钟计时器 - 选择时间间隔:
每1分钟
- 选择要运行的函数:
- 保存后按页面提示完成Google账号权限验证即可
步骤4:表格内使用公式
所有需要展示随机冷笑话的单元格,输入公式=LOL(Sheet1!A1)即可,每分钟会自动刷新新的笑话内容。
提示:如果不想让控制单元格的数值显示影响页面美观,可以把控制单元格的字体颜色设置为和背景色一致,或者放到单独的隐藏工作表中。
内容的提问来源于stack exchange,提问作者EnderCodesLol
相关产品推荐
相关产品推荐

