Last active
January 15, 2020 23:03
-
-
Save adz/68a786272a4d24b41361d56501cba59f to your computer and use it in GitHub Desktop.
Background jobs recurring with delay
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
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