如何限制我的一些 tmux 插件进行的网络调用?

How can I throttle the network calls that some of my tmux plugins make?

我有几个 tmux 脚本,它们在我的 tmux 状态栏中显示 ip、时间、主机名等信息。例如,ip 脚本如下所示:

#!/bin/bash

runSegment() {
  # check for a network connection
  nc -z 8.8.8.8 53  >/dev/null 2>&1
  online=$?

  if [ $online -eq 0 ]; then
    # get ip
    ip=`curl icanhazip.com`
    echo -n "  ${ip}"
  else
    echo ""
  fi
}

export -f runSegment

它检查网络连接,如果有则获取 ip。现在我的 tmux 状态栏设置为每五秒刷新一次 (tmux set-option -g status-interval 5)。但是每五秒向这些服务发出一次网络请求似乎有点过分了。

但是,我想保持电池状态和时间每五秒更新一次,因此将状态间隔设置为五分钟左右不是一个选项。

那么我如何让这个脚本 return 缓存值,并且只在五分钟左右刷新该值?我假设我需要在 bash 中解决这个问题,但我需要为此设置内部状态,并且随着这个脚本每次重新获得 运行,我不确定如何去做它。

所以这有效:

#!/bin/bash

runSegment() {
  # check if online and assign exit code to variable
  nc -z 8.8.8.8 53  >/dev/null 2>&1
  local online=$?

  if [ $online -eq 0 ]; then
    # check how many seconds ago ip was retrieved
    local lastmod=$(( $(date +%s) - $(stat -f%c ~/.current-ip) ))

    # if longer than five minutes ago refresh the value and echo that
    if [ $lastmod -gt 300 ]; then
      local ip=$(curl icanhazip.com)
      echo ${ip} > $HOME/.current-ip
      echo -n "  ${ip}"

    # otherwise use the cached value
    else
      local ip=$(cat $HOME/.current-ip)
      echo -n "  ${ip}"
    fi

  # return empty value if there's no connection
  else
    echo ""
  fi
}

export -f runSegment