Skip to content

Instantly share code, notes, and snippets.

@jltrem
Last active October 5, 2019 14:53
Show Gist options
  • Save jltrem/0fa63472ed597488c2f4467893471c71 to your computer and use it in GitHub Desktop.
Save jltrem/0fa63472ed597488c2f4467893471c71 to your computer and use it in GitHub Desktop.
module AsyncPeriodicWork =
let createCanceller () =
new System.Threading.CancellationTokenSource()
let start (canceller:System.Threading.CancellationTokenSource) (intervalMillis:int) (work:(unit->unit)) (onFault:(System.Exception->unit) option)=
let loop = async {
printfn "starting..."
try
while true do
work()
do! Async.Sleep intervalMillis
with
| ex -> match onFault with
| Some(handler) -> ex |> handler
| None -> ()
printfn "exiting"
}
Async.Start (loop, canceller.Token)
let startCancellable (intervalMillis:int) (work:(unit->unit)) (onFault:(System.Exception->unit) option) =
let canceller = createCanceller()
start canceller intervalMillis work onFault
canceller
module examples =
let run1 () =
let printTimestamp x =
fun () -> printfn "%s %A" x System.DateTime.Now
let cts = AsyncPeriodicWork.createCanceller()
AsyncPeriodicWork.start cts 500 (printTimestamp "A") None
AsyncPeriodicWork.start cts 100 (printTimestamp "B") None
//System.Threading.Thread.Sleep(2000)
//cts.Cancel()
cts
let run2 () =
let stopwatch = System.Diagnostics.Stopwatch()
stopwatch.Start()
let cts = AsyncPeriodicWork.startCancellable 100 (fun () -> printfn "%A" stopwatch.ElapsedMilliseconds) None
//System.Threading.Thread.Sleep(1000)
//cts.Cancel()
cts
let run3 () =
let work = fun () ->
match System.Random().Next() % 10 with
| x when x < 8 -> printfn "random is %A" x
| _ -> failwith "foobar"
let cts = AsyncPeriodicWork.startCancellable 100 work (Some(fun ex -> printfn "%A!" ex.Message))
cts
let cancelAfterMillis (millis:int) (cts:System.Threading.CancellationTokenSource) =
System.Threading.Thread.Sleep(millis)
cts.Cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment