【问题标题】:Randomize Utilities.sleep function随机化 Utilities.sleep 函数
【发布时间】:2021-06-23 02:16:18
【问题描述】:

如何在 Google Script 中随机化 Utilities.sleep 函数? 我有一个具有缩短链接功能的 Google 表格。脚本如下:

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);
  return shortUrl;}

但是当我运行它(获取大约 100 个网址)时,它会抛出错误:

异常:一天内服务调用次数过多:urlfetch。 (线 11).

在 Stackoverflow 中搜索和询问后,他们建议我使用 Utilities.sleep(5000);

所以代码变成了这样:

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);
  Utilities.sleep(5000);
  return shortUrl;}

但是,它只是等待错误 5 秒。如何随机化Utilities.sleep(5000); 的值?

类似:

Utilities.sleep(RANDOM_FROM_1MINS-5MIN);

【问题讨论】:

    标签: javascript google-apps-script google-sheets


    【解决方案1】:

    您可以使用Math.random() 生成随机数。在您的情况下,考虑到 1 到 5 分钟之间的间隔,您可以使用:

    const min = 60000; // milliseconds in one minute
    const max = 300000; // milliseconds in five minutes
    const waitTime = Math.floor(Math.random() * (max - min + 1) ) + min;
    Utilities.sleep(waitTime);
    

    请注意,脚本一次只能运行 six minutes,因此使用 5 分钟可能不是一个好主意。

    【讨论】:

    • 我会尝试修改为 3 分钟。稍后通知您
    • 效果很好!但是自定义功能只能工作 30 秒。所以我将最大值修改为 20000,以便为脚本提供额外的 10 秒。非常感谢!
    猜你喜欢
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多