Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. module AsyncPeriodicWork =
  2.  
  3. let createCanceller () =
  4. new System.Threading.CancellationTokenSource()
  5.  
  6. let start (canceller:System.Threading.CancellationTokenSource) (intervalMillis:int) (work:(unit->unit)) (onFault:(System.Exception->unit) option)=
  7.  
  8. let loop = async {
  9. printfn "starting..."
  10. try
  11. while true do
  12. work()
  13. do! Async.Sleep intervalMillis
  14. with
  15. | ex -> match onFault with
  16. | Some(handler) -> ex |> handler
  17. | None -> ()
  18. printfn "exiting"
  19. }
  20.  
  21. Async.Start (loop, canceller.Token)
  22.  
  23. let startCancellable (intervalMillis:int) (work:(unit->unit)) (onFault:(System.Exception->unit) option) =
  24.  
  25. let canceller = createCanceller()
  26. start canceller intervalMillis work onFault
  27. canceller
  28.  
  29.  
  30.  
  31. module examples =
  32.  
  33. let run1 () =
  34.  
  35. let printTimestamp x =
  36. fun () -> printfn "%s %A" x System.DateTime.Now
  37.  
  38. let cts = AsyncPeriodicWork.createCanceller()
  39. AsyncPeriodicWork.start cts 500 (printTimestamp "A") None
  40. AsyncPeriodicWork.start cts 100 (printTimestamp "B") None
  41. //System.Threading.Thread.Sleep(2000)
  42. //cts.Cancel()
  43. cts
  44.  
  45. let run2 () =
  46.  
  47. let stopwatch = System.Diagnostics.Stopwatch()
  48. stopwatch.Start()
  49. let cts = AsyncPeriodicWork.startCancellable 100 (fun () -> printfn "%A" stopwatch.ElapsedMilliseconds) None
  50. //System.Threading.Thread.Sleep(1000)
  51. //cts.Cancel()
  52. cts
  53.  
  54. let run3 () =
  55.  
  56. let work = fun () ->
  57. match System.Random().Next() % 10 with
  58. | x when x < 8 -> printfn "random is %A" x
  59. | _ -> failwith "foobar"
  60.  
  61. let cts = AsyncPeriodicWork.startCancellable 100 work (Some(fun ex -> printfn "%A!" ex.Message))
  62. cts
  63.  
  64. let cancelAfterMillis (millis:int) (cts:System.Threading.CancellationTokenSource) =
  65. System.Threading.Thread.Sleep(millis)
  66. cts.Cancel()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement