Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type Timer = { incomingTasks: Ch<DateTime * Alt<unit> * IVar<Alt<unit>>> }
- module Timer =
- type Task = {
- wakeTime: DateTime
- cancel: Alt<unit>
- fire: IVar<unit>
- }
- let takeFirst tasks =
- match tasks with
- | [] -> None, []
- | xs -> xs |> List.head |> Some, xs |> List.tail
- let create () = { incomingTasks = Ch () }
- let start timer =
- let rec timerLoop (currentTask, nextTasks) =
- Alt.choose (seq {
- match currentTask with
- | Some task ->
- yield task.cancel ^->. (nextTasks |> takeFirst)
- let waitTime = task.wakeTime - DateTime.Now
- yield
- (if TimeSpan.Compare (waitTime, TimeSpan.Zero) <= 0 then
- Alt.always ()
- else
- (timeOut waitTime))
- ^=>. (task.fire *<= () >>- (fun _ -> printfn "event fired") >>-. (nextTasks |> takeFirst))
- | None -> ()
- yield Ch.take timer.incomingTasks ^=> (fun (wakeTime, cancel, res) ->
- let fire = IVar ()
- let newTask = { wakeTime = wakeTime; cancel = cancel; fire = fire }
- res *<= (fire |> IVar.read) >>- fun _ ->
- currentTask |> Option.fold (fun l x -> x::l) (newTask::nextTasks)
- |> List.sortBy (fun task -> task.wakeTime)
- |> takeFirst)
- })
- >>= timerLoop
- timerLoop (None, []) >>- (fun _ -> printfn "TIMER STARTED")
- let submit wakeTime cancel timer =
- let res = IVar ()
- timer.incomingTasks *<+ (wakeTime, cancel, res)
- >>=. res
- [<EntryPoint>]
- let main argv =
- // let stop = IVar<string> ()
- // // let x = printDelay |> until stop 10 |> startIgnore
- // let promiseJob = printDelay |> until stop 0 |> Promise.start >>= Promise.read >>- (fun r -> Console.WriteLine (r)) |> startIgnore
- // // let r = promiseJob |> startIgnore
- // Console.ReadLine () |> ignore
- // stop *<= "asdf" |> run
- // Console.ReadLine () |> ignore
- printfn "Start: %A" DateTime.Now
- let timer = Timer.create ()
- timer |> Timer.start |> startIgnore
- let wakeTime = DateTime.Now + (TimeSpan.FromSeconds 1.)
- timer |> Timer.submit wakeTime (Alt.never ()) >>= id >>- (fun _ -> printfn "EVENT: %A" DateTime.Now) |> startIgnore
- Console.ReadLine () |> ignore
- 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement