Skip to content

Instantly share code, notes, and snippets.

@SP3269
Created January 27, 2021 04:32
Show Gist options
  • Save SP3269/4c6d998cc81b211075568ba5528749db to your computer and use it in GitHub Desktop.
Save SP3269/4c6d998cc81b211075568ba5528749db to your computer and use it in GitHub Desktop.
# Simple backoff in PowerShell
# Executes a scriptblock - the Code parameter
# In case of a blocking error, retries - the number of retries and seconds to wait before each is the Intervals parameter (array)
# Returns the result of the code invocation of throws the last error if run out of the backoffs
function Invoke-WithBackoff {
[CmdletBinding()]
param (
[Parameter()] [scriptblock]$Code,
[Parameter()] [float[]]$Intervals
)
foreach ($t in $Intervals) {
try {
$res = &$Code
return $res
}
catch {
Write-Verbose "Backing off for $t seconds"
Start-Sleep -Seconds $t
}
}
throw (Get-Error)
}
$code = {
$failprobability = 0.8
if ((Get-Random 1.0) -gt $failprobability) {
"200"
} else {
throw "500"
}
}
$retries = @(1,1.5,2,3,5)
Invoke-WithBackoff -Intervals $retries -Code $code -Verbose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment