-1

I need to run a curl request to locahost at least once in every 30 mins. So the command will be curl http://localhost:8080.

The catch here is, I want to select a time randomly between 5min - 30 min and then execute the curl command. The pseudo-code might look like this

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

A detailed answer would be nice since I don't have much knowledge about linux.

asdlfkjlkj
  • 2,258
  • 6
  • 20
  • 28

2 Answers2

1
while true; do
    sleep $(((RANDOM%25+5)*60))
    curl http://localhost:8080
done
user3486184
  • 2,147
  • 3
  • 26
  • 28
1

If you run above script, you must run as background process and make sure it will not be killed by something (OS, other users,...)

Another way is use cronjob to trigger automatically but the script is more complex.

Cronjob setting:

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

Shell script 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)"

I commented out in line so you can read it easily. **

Update: Importance: file execute_time must has initial value. For example, the current minute of first time you execute.

**

Bui Anh Tuan
  • 910
  • 6
  • 12