Linux:随机每50分钟运行一次命令

时间:2017-08-17 23:52:41

标签: linux curl

我需要每30分钟至少运行一次针对locahost的卷曲请求。所以命令将是curl http://localhost:8080

这里的问题是,我想在5分钟到30分钟之间随机选择一个时间,然后执行curl命令。伪代码可能看起来像这样

while(true)
n = random number between 5-30
run curl http://localhost:8080 after 'n' minutes

详细的答案很好,因为我对linux没有太多了解。

2 个答案:

答案 0 :(得分:1)

如果你运行上面的脚本,你必须作为后台进程运行,并确保它不会被某些东西杀死(操作系统,其他用户......)

另一种方法是使用cronjob自动触发,但脚本更复杂。

Cronjob设定:

* * * * * bash test_curl.sh >> log_file.log

Shell脚本test_curl.sh:

#!/bin/bash

# Declare some variable
EXECUTE_TIME_FILE_PATH="./execute_time"

# load expected execute time
EXPECTED_EXECUTE_TIME=$(cat $EXECUTE_TIME_FILE_PATH)

echo "Start at $(date)"

# calculate current time and compare with expected execute time
CURRENT_MINUTE_OF_TIME=$(date +'%M')

if [[ "$EXPECTED_EXECUTE_TIME" == "$CURRENT_MINUTE_OF_TIME"  ]];
then
  curl http://localhost:8080
  # Random new time from 5 -> 30
  NEXT_RANDOM=$((RANDOM%25+5))
  # Get current time
  CURRENT_TIME=$(date +'%H:%M')
  # Calculate next expected execute time = Current Time + Next Random
  NEXT_EXPECTED_EXECUTE_TIME=$(date -d "$CURRENT_TIME $NEXT_RANDOM minutes" +'%M')
  # Save to file
  echo -n $NEXT_EXPECTED_EXECUTE_TIME > $EXECUTE_TIME_FILE_PATH
  echo "Next Executed time is $(date -d "$CURRENT_TIME $NEXT_RANDOM minutes" +'%H:%M')"
else
  echo "This $(date +'%H:%M') is not expected time to run test"
fi

echo "End at $(date)"

我排队了,所以你可以轻松阅读。 **

  

更新:重要性:文件execute_time必须具有初始值。对于   例如,您第一次执行的当前分钟。

**

答案 1 :(得分:0)

while true; do
    sleep $(((RANDOM%25+5)*60))
    curl http://localhost:8080
done