Created
April 11, 2016 19:07
-
-
Save non7top/217db3372097067ea14bbb13574b1e4a to your computer and use it in GitHub Desktop.
bash function to retry with backoff
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 with_backoff { | |
# http://stackoverflow.com/questions/8350942/how-to-re-run-the-curl-command-automatically-when-the-error-occurs | |
# by phs | |
# | |
# The retry count is given by ATTEMPTS (default 5), the initial backoff | |
# timeout is given by TIMEOUT in seconds (default 1.) | |
# | |
# Successive backoffs double the timeout. | |
local max_attempts=${ATTEMPTS-5} | |
local timeout=${TIMEOUT-1} | |
local attempt=0 | |
local exitCode=0 | |
while (( $attempt < $max_attempts )) | |
do | |
set +e | |
"$@" | |
exitCode=$? | |
set -e | |
if [[ $exitCode == 0 ]] | |
then | |
break | |
fi | |
echo "Failure! Retrying in $timeout.." 1>&2 | |
sleep $timeout | |
attempt=$(( attempt + 1 )) | |
timeout=$(( timeout * 2 )) | |
done | |
if [[ $exitCode != 0 ]] | |
then | |
echo "You've failed me for the last time! ($@)" 1>&2 | |
fi | |
return $exitCode | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment