You need to enable JavaScript to run this app. 如何在Google Script中随机设置Utilities.sleep的等待时长
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 19:45:03