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: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
let retry maxRetries before f =
    let rec loop retriesRemaining =
        try
            f ()
        with _ when retriesRemaining > 0 ->
            before ()
            loop (retriesRemaining-1)
    loop maxRetries

// Example

let act () : unit = printfn "trying"; invalidOp "Problem"
act |> retry 2 (fun () ->  printfn "retrying";  System.Threading.Thread.Sleep 50) 

(*Yields:

trying
retrying
trying
retrying
trying
System.InvalidOperationException: Problem *)
val retry : maxRetries:int -> before:(unit -> unit) -> f:(unit -> 'a) -> 'a

Full name: Script.retry
val maxRetries : int
val before : (unit -> unit)
val f : (unit -> 'a)
val loop : (int -> 'a)
val retriesRemaining : int
val act : unit -> unit

Full name: Script.act
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val invalidOp : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.invalidOp
namespace System
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

More information

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