Skip to content

Instantly share code, notes, and snippets.

@adz
Last active January 15, 2020 23:03
Show Gist options
  • Save adz/68a786272a4d24b41361d56501cba59f to your computer and use it in GitHub Desktop.
Save adz/68a786272a4d24b41361d56501cba59f to your computer and use it in GitHub Desktop.
Background jobs recurring with delay
module Async
let delayBy (timespan : TimeSpan) a =
async {
do! Async.Sleep (Convert.ToInt32 timespan.TotalMilliseconds)
return! a
}
let rec repeat a =
async {
do! a
return! repeat a
}
let catchAndLog log logError name a =
async {
log <| sprintf "[%s] Starting..." name
let! result = Async.Catch a
match result with
| Choice1Of2 _ ->
log <| sprintf "[%s] Completed normally." name
()
| Choice2Of2 ex ->
logError (sprintf "[%s] Unhandled exception" name, ex)
()
}
let catchAndPrint : string -> Async<unit> -> Async<unit> =
catchAndLog (printfn "%A") (printfn "%A")
// usage
myAsyncBackroundJob
|> Async.catchAndPrint "My background Job"
|> Async.delayBy aTimeSpan
|> Async.repeat
|> Async.Start // or Async.Parallel with others
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment