Created
January 12, 2021 10:10
-
-
Save regeda/2847dc21ead224d92cdc5437e3ba87cd to your computer and use it in GitHub Desktop.
Backoff in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function backoff_delay { | |
local -r -i factor=${BACKOFF_FACTOR-2} | |
local -i min=$(($1*$factor)) | |
local -r -i max=$2 | |
if [[ $max < $min ]]; then | |
min=$max | |
fi | |
echo $min | |
} | |
function with_backoff { | |
local -r -i max_attempts=${BACKOFF_MAX_ATTEMPTS-3} | |
local -i attempts=0 | |
local -r -i max_delay=${BACKOFF_MAX_DELAY-30} | |
local -i delay=1 | |
local exit_code=1 | |
while [[ $((attempts++)) < $max_attempts ]]; do | |
"$@" && return 0 | |
exit_code=$? | |
sleep $delay | |
delay=$(backoff_delay $delay $max_delay) | |
done | |
return $exit_code | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment