ENV : GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu) (It's old)
- I want every loop takes equal time.
- The loop never stops
- The
api_call
function normally takes about 1s~5s. - The API call may seldomly hang until 60s-timeout due to network problem.
My script A
TIMEFORMAT=%R
while true; do
time=$(date +'%F %T')
api_result=$( { time api_call; } 2>api_runtime.txt )
api_runtime=$(cat api_runtime.txt)
echo "${time} ${api_result}"
sleep (( 10 - ${api_runtime} ))
done
I think Scrit A will do the job until someday network gets slow and the loop gets out of sync.
My script B
TIMEFORMAT=%R
while true; do
time=$(date +'%F %T')
api_result=$( api_call & )
sleep 10
echo "${time} ${api_result:-No response}"
done
Script B seems to also work at the moment, but I'm not sure if it's safe for the next loop when api_call
takes more than 10 seconds.
How do I achieve this?