2 people like it.

Retry loop, no tricks

Less-nonsense 8-line retry function that will retry a function a specified up to `maxRetries` times while it throws. After the retries, any remaining exception is allowed to propagate. Accepts a before function to allow you to wait/report when a retry is taking place

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
let retryWithSleep (sleepSpan:System.TimeSpan) maxRetries f =
    let rec loop retriesRemaining =
        try
            f()
        with _ when retriesRemaining <> 0 ->
            System.Threading.Thread.Sleep sleepSpan
            loop <| retriesRemaining-1 
    loop maxRetries
val retryWithSleep : sleepSpan:System.TimeSpan -> maxRetries:int -> f:(unit -> 'a) -> 'a

Full name: Script.retryWithSleep
val sleepSpan : System.TimeSpan
namespace System
Multiple items
type TimeSpan =
  struct
    new : ticks:int64 -> TimeSpan + 3 overloads
    member Add : ts:TimeSpan -> TimeSpan
    member CompareTo : value:obj -> int + 1 overload
    member Days : int
    member Duration : unit -> TimeSpan
    member Equals : value:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member Hours : int
    member Milliseconds : int
    member Minutes : int
    ...
  end

Full name: System.TimeSpan

--------------------
System.TimeSpan()
System.TimeSpan(ticks: int64) : unit
System.TimeSpan(hours: int, minutes: int, seconds: int) : unit
System.TimeSpan(days: int, hours: int, minutes: int, seconds: int) : unit
System.TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int) : unit
val maxRetries : int
val f : (unit -> 'a)
val loop : (int -> 'a)
val retriesRemaining : int
namespace System.Threading
Multiple items
type Thread =
  inherit CriticalFinalizerObject
  new : start:ThreadStart -> Thread + 3 overloads
  member Abort : unit -> unit + 1 overload
  member ApartmentState : ApartmentState with get, set
  member CurrentCulture : CultureInfo with get, set
  member CurrentUICulture : CultureInfo with get, set
  member DisableComObjectEagerCleanup : unit -> unit
  member ExecutionContext : ExecutionContext
  member GetApartmentState : unit -> ApartmentState
  member GetCompressedStack : unit -> CompressedStack
  member GetHashCode : unit -> int
  ...

Full name: System.Threading.Thread

--------------------
System.Threading.Thread(start: System.Threading.ThreadStart) : unit
System.Threading.Thread(start: System.Threading.ParameterizedThreadStart) : unit
System.Threading.Thread(start: System.Threading.ThreadStart, maxStackSize: int) : unit
System.Threading.Thread(start: System.Threading.ParameterizedThreadStart, maxStackSize: int) : unit
System.Threading.Thread.Sleep(timeout: System.TimeSpan) : unit
System.Threading.Thread.Sleep(millisecondsTimeout: int) : unit
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/o0
Posted:10 years ago
Author:Ruben Bartelink
Tags: retry , sleep , recursion , exceptions