多个卷曲与限制并行

时间:2018-03-29 13:33:29

标签: bash unix curl parallel-processing

我有一个json文件,其中包含url(以及其他内容)的条目,我使用curl检索。 我希望能够一次多次运行循环以加快速度,但也要限制并行卷曲的数量,以避免被远程服务器踢出。 现在,我的代码就像

  jq -r '.entries[] | select(.enabled != false) | .id,.unitUrl' $fileIndexFeed | \
  while read unitId; do
    read -r unitUrl
    if ! in_array tabAnnoncesExistantesIds $unitId; then
      fullUnitUrl="$unitUrlBase$unitUrl"
      unitFile="$unitFileBase$unitId.json"
      if [ ! -f $unitFile ]; then
        curl -H "Authorization:$authMethod $encodedHeader" -X GET $fullUnitUrl -o $unitFile
      fi
    fi
   done

如果我使用简单的&在我的卷曲结束时,它将运行大量的并发请求,我可能会被踢。 所以,问题是(我想):如何知道卷曲与&已经完成了它的工作?如果我能够检测到,那么我想我可以测试,增加和减少一个变量,告诉运行卷发的数量。

由于

2 个答案:

答案 0 :(得分:3)

使用 GNU Parallel 来控制并行作业的数量。将curl命令写入文件,以便查看并检查它们:

commands.txt

curl "something" "somehow" "toSomewhere"
curl "somethingelse" "someotherway" "toSomewhereElse"

然后,如果您希望一次运行的作业不超过8个,请运行:

parallel -j 8 --eta -a commands.txt

或者您可以将命令写入 GNU Parallel stdin

jq ... | while read ...; do
    printf "curl ..." 
done | parallel -j 8 

答案 1 :(得分:1)

使用Bash功能:

doit() {
  unitId="$1"
  unitUrl="$2"
  if ! in_array tabAnnoncesExistantesIds $unitId; then
    fullUnitUrl="$unitUrlBase$unitUrl"
    unitFile="$unitFileBase$unitId.json"
    if [ ! -f $unitFile ]; then
      curl -H "Authorization:$authMethod $encodedHeader" -X GET $fullUnitUrl -o $unitFile
    fi
  fi
}

jq -r '.entries[] | select(.enabled != false) | .id,.unitUrl' $fileIndexFeed |
  env_parallel -N2 doit

env_parallel将导入环境,因此所有shell变量都可用。

相关问题