如何在Google Script中随机设置Utilities.sleep的等待时长
你可以通过Math.random()生成指定区间的随机毫秒值,直接替换固定的延迟参数即可:
1分钟对应的毫秒值为60 * 1000 = 60000,5分钟对应的毫秒值为5 * 60 * 1000 = 300000,生成1-5分钟随机毫秒数的公式为:Math.floor(Math.random() * (300000 - 60000 + 1)) + 60000
修改后的完整代码如下:
function ShortURL(longUrl) { const url = "http://example.com/api/url/add"; const params = { method: "post", headers: { Authorization: "Token MYTOKEN" }, contentType: "application/json", payload: JSON.stringify({ "url": longUrl }) }; const res = UrlFetchApp.fetch(url, params); var shortUrl = JSON.parse(res.getContentText()).short; Logger.log(shortUrl); // 生成1-5分钟随机延迟(单位:毫秒) const randomDelay = Math.floor(Math.random() * (300000 - 60000 + 1)) + 60000; Utilities.sleep(randomDelay); return shortUrl; }
补充说明:如果调整延迟后仍然触发报错,可先确认报错来源:如果是Google服务的UrlFetch日配额超限,消费级账号日配额一般为20000次,超出后只能次日再调用;如果是短链API的频率限制,也可以先查询API文档看是否支持批量提交长链接,单次请求处理多条数据能大幅减少调用次数,也能避免过长的等待时间。
内容的提问来源于stack exchange,提问作者Faro
相关产品推荐
相关产品推荐

