【问题标题】:Conky runs the same curl request multiple times per intervalConky 每个时间间隔多次运行相同的 curl 请求
【发布时间】:2014-08-05 01:41:08
【问题描述】:

API 以包含所有内容的 XML 文件进行响应。我希望该 XML 中的一些数据出现在我的 conky 部分中

我有一个 bash 脚本来获取和解析数据。好像

#!/bin/sh
if [ -z $1 ]; then
        echo "missing arguments"
        exit 0;
fi
curl -s http://example.com/api.php | xmllint --xpath "//${1}/text()" -

在 .conkyrc 我有

${color slate grey}Number of cats: ${color }
${execi 3600 myscript.sh cats}

${color slate grey}Color of the day: ${color }
${execi 3600 myscript.sh color}

${color slate grey}Some other stuff: ${color }
${execi 3600 myscript.sh stuff}

这工作很好,但即使我需要的所有数据第一次传递,我也会在每个时间间隔向 API 发出 3 个请求。

显而易见的解决方案是更改 bash 脚本以将 API 响应保存到带有时间戳的临时文件中。无论脚本在哪里运行,首先检查临时文件的时间戳以查看它是否已过期(或不存在)。如果是这样,请将其删除并发出新的 curl 请求。如果不是,则用

交换 curl 语句
cat tempfile.xml | xmllint

但我不喜欢到处乱放临时文件或担心潜在的竞争条件。有没有办法从我的脚本中返回我需要的所有数据并将其提供给 conky 以存储为 conky 变量,然后将它们打印在正确的位置?或者更广泛地说,我应该如何改进这一点?

【问题讨论】:

  • 如果脚本输出包含${color slate grey} 标记,它们是否可以正常工作?因为如果他们这样做了,那么您可以将所有代码移动到 shell 脚本,然后将 curl 输出保存到一个变量中,并根据需要将 echo 保存到 xmllint。 (尽管即使运行 xmllint 三次也是不必要的,因为您可以编写一个 xsl 转换来一次完成整个事情。)

标签: bash shell curl conky


【解决方案1】:

您可以修改脚本以使用缓存:

#!/bin/sh

CACHE_FILE=/var/cache/api.data

check_missing_arg() {
    if [ -z "$1" ]; then
        echo "missing arguments"
        exit 0
    fi
}

if [ "$1" = --use-cache ] && [ -f "$CACHE_FILE" ]; then
    shift
    check_missing_arg "$@"
    xmllint --xpath "//${1}/text()" "$CACHE_FILE"
elif [ "$1" = --store-cache ]; then
    shift
    check_missing_arg "$@"
    curl -s http://example.com/api.php > "$CACHE_FILE"
    xmllint --xpath "//${1}/text()" "$CACHE_FILE"
else
    check_missing_arg "$@"
    curl -s http://example.com/api.php | xmllint --xpath "//${1}/text()" -
fi

在你的.conkyrc:

${color slate grey}Number of cats: ${color }
${execi 3600 myscript.sh --store-cache cats}

${color slate grey}Color of the day: ${color }
${execi 3600 myscript.sh --use-cache color}

${color slate grey}Some other stuff: ${color }
${execi 3600 myscript.sh --use-cache stuff}
  • 最好将缓存写入tmpfs。一些发行版默认将/dev/shm 挂载为tmpfs

【讨论】:

  • 哈,只是让第一个实例包含一个参数来清除以前的缓存。多么简单的想法,我不敢相信我没有想到。谢谢!我将 /tmp 挂载为 tmpfs,所以我打算使用它。
猜你喜欢
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
相关资源
最近更新 更多