9 people like it.
Like the snippet!
Agent Based Scheduler
An agent based scheduler, can be sent a single schedule message (ScheduleOnce) and multiple schedule message (Schedule).
The schedule messages comprise of a function to receive the message, the message, an initial TimeSpan before the message is scheduled, and another timespan for the schedule repeat.
Check out my blog below for more details:
http://bit.ly/mK4prb
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
|
module AgentUtilities
open System
open System.Threading
//Agent alias for MailboxProcessor
type Agent<'T> = MailboxProcessor<'T>
/// Two types of Schedule messages that can be sent
type ScheduleMessage<'a> =
| Schedule of ('a -> unit) * 'a * TimeSpan * TimeSpan * CancellationTokenSource AsyncReplyChannel
| ScheduleOnce of ('a -> unit) * 'a * TimeSpan * CancellationTokenSource AsyncReplyChannel
/// An Agent based scheduler
type SchedulerAgent<'a>()=
let scheduleOnce delay msg receiver (cts: CancellationTokenSource)=
async { do! Async.Sleep(delay)
if (cts.IsCancellationRequested)
then cts.Dispose()
else msg |> receiver }
let scheduleMany initialDelay msg receiver delayBetween cts=
let rec loop time (cts: CancellationTokenSource) =
async { do! Async.Sleep(time)
if (cts.IsCancellationRequested)
then cts.Dispose()
else msg |> receiver
return! loop delayBetween cts}
loop initialDelay cts
let scheduler = Agent.Start(fun inbox ->
let rec loop() = async {
let! msg = inbox.Receive()
let cs = new CancellationTokenSource()
match msg with
| Schedule(receiver, msg:'a, initialDelay, delayBetween, replyChan) ->
Async.StartImmediate(scheduleMany
(int initialDelay.TotalMilliseconds)
msg
receiver
(int delayBetween.TotalMilliseconds)
cs )
replyChan.Reply(cs)
return! loop()
| ScheduleOnce(receiver, msg:'a, delay, replyChan) ->
Async.StartImmediate(scheduleOnce
(int delay.TotalMilliseconds)
msg
receiver
cs)
replyChan.Reply(cs)
return! loop()
}
loop())
///Schedules a message to be sent to the receiver after the initialDelay.
/// If delaybetween is specified then the message is sent reoccuringly at the delaybetween interval.
member this.Schedule(receiver, msg, initialDelay, ?delayBetween) =
let buildMessage replyChan =
match delayBetween with
| Some(x) -> Schedule(receiver,msg,initialDelay, x, replyChan)
| _ -> ScheduleOnce(receiver,msg,initialDelay, replyChan)
scheduler.PostAndReply (fun replyChan -> replyChan |> buildMessage)
|
module AgentUtilities
namespace System
namespace System.Threading
type Agent<'T> = MailboxProcessor<'T>
Full name: AgentUtilities.Agent<_>
Multiple items
type MailboxProcessor<'Msg> =
interface IDisposable
new : body:(MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken:CancellationToken -> MailboxProcessor<'Msg>
member Post : message:'Msg -> unit
member PostAndAsyncReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> Async<'Reply>
member PostAndReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> 'Reply
member PostAndTryAsyncReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> Async<'Reply option>
member Receive : ?timeout:int -> Async<'Msg>
member Scan : scanner:('Msg -> Async<'T> option) * ?timeout:int -> Async<'T>
member Start : unit -> unit
member TryPostAndReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> 'Reply option
...
Full name: Microsoft.FSharp.Control.MailboxProcessor<_>
--------------------
new : body:(MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken:CancellationToken -> MailboxProcessor<'Msg>
type ScheduleMessage<'a> =
| Schedule of ('a -> unit) * 'a * TimeSpan * TimeSpan * AsyncReplyChannel<CancellationTokenSource>
| ScheduleOnce of ('a -> unit) * 'a * TimeSpan * AsyncReplyChannel<CancellationTokenSource>
Full name: AgentUtilities.ScheduleMessage<_>
Two types of Schedule messages that can be sent
union case ScheduleMessage.Schedule: ('a -> unit) * 'a * TimeSpan * TimeSpan * AsyncReplyChannel<CancellationTokenSource> -> ScheduleMessage<'a>
type unit = Unit
Full name: Microsoft.FSharp.Core.unit
Multiple items
type TimeSpan =
struct
new : ticks:int64 -> TimeSpan + 3 overloads
member Add : ts:TimeSpan -> TimeSpan
member CompareTo : value:obj -> int + 1 overload
member Days : int
member Duration : unit -> TimeSpan
member Equals : value:obj -> bool + 1 overload
member GetHashCode : unit -> int
member Hours : int
member Milliseconds : int
member Minutes : int
...
end
Full name: System.TimeSpan
--------------------
TimeSpan()
TimeSpan(ticks: int64) : unit
TimeSpan(hours: int, minutes: int, seconds: int) : unit
TimeSpan(days: int, hours: int, minutes: int, seconds: int) : unit
TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int) : unit
Multiple items
type CancellationTokenSource =
new : unit -> CancellationTokenSource
member Cancel : unit -> unit + 1 overload
member Dispose : unit -> unit
member IsCancellationRequested : bool
member Token : CancellationToken
static member CreateLinkedTokenSource : [<ParamArray>] tokens:CancellationToken[] -> CancellationTokenSource + 1 overload
Full name: System.Threading.CancellationTokenSource
--------------------
CancellationTokenSource() : unit
type AsyncReplyChannel<'Reply>
member Reply : value:'Reply -> unit
Full name: Microsoft.FSharp.Control.AsyncReplyChannel<_>
union case ScheduleMessage.ScheduleOnce: ('a -> unit) * 'a * TimeSpan * AsyncReplyChannel<CancellationTokenSource> -> ScheduleMessage<'a>
Multiple items
type SchedulerAgent<'a> =
new : unit -> SchedulerAgent<'a>
member Schedule : receiver:('a -> unit) * msg:'a * initialDelay:TimeSpan * ?delayBetween:TimeSpan -> CancellationTokenSource
Full name: AgentUtilities.SchedulerAgent<_>
An Agent based scheduler
--------------------
new : unit -> SchedulerAgent<'a>
val scheduleOnce : (int -> 'a -> 'b -> CancellationTokenSource -> Async<unit>)
val delay : int
val msg : 'a
val receiver : 'b
val cts : CancellationTokenSource
val async : AsyncBuilder
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken
Full name: Microsoft.FSharp.Control.Async
--------------------
type Async<'T>
Full name: Microsoft.FSharp.Control.Async<_>
static member Async.Sleep : millisecondsDueTime:int -> Async<unit>
property CancellationTokenSource.IsCancellationRequested: bool
CancellationTokenSource.Dispose() : unit
val scheduleMany : ('a -> 'b -> 'c -> 'd -> 'e -> 'f)
val initialDelay : 'a
val msg : 'b
val receiver : 'c
val delayBetween : 'd
val cts : 'e
val loop : (int -> CancellationTokenSource -> Async<unit>)
val time : int
val scheduler : MailboxProcessor<ScheduleMessage<'a>>
static member MailboxProcessor.Start : body:(MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken:CancellationToken -> MailboxProcessor<'Msg>
val inbox : MailboxProcessor<ScheduleMessage<'a>>
val loop : (unit -> Async<'b>)
val msg : ScheduleMessage<'a>
member MailboxProcessor.Receive : ?timeout:int -> Async<'Msg>
val cs : CancellationTokenSource
val receiver : ('a -> unit)
val initialDelay : TimeSpan
val delayBetween : TimeSpan
val replyChan : AsyncReplyChannel<CancellationTokenSource>
static member Async.StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
Multiple items
val int : value:'T -> int (requires member op_Explicit)
Full name: Microsoft.FSharp.Core.Operators.int
--------------------
type int = int32
Full name: Microsoft.FSharp.Core.int
--------------------
type int<'Measure> = int
Full name: Microsoft.FSharp.Core.int<_>
property TimeSpan.TotalMilliseconds: float
member AsyncReplyChannel.Reply : value:'Reply -> unit
val delay : TimeSpan
val this : SchedulerAgent<'a>
member SchedulerAgent.Schedule : receiver:('a -> unit) * msg:'a * initialDelay:TimeSpan * ?delayBetween:TimeSpan -> CancellationTokenSource
Full name: AgentUtilities.SchedulerAgent`1.Schedule
Schedules a message to be sent to the receiver after the initialDelay.
If delaybetween is specified then the message is sent reoccuringly at the delaybetween interval.
val delayBetween : TimeSpan option
val buildMessage : (AsyncReplyChannel<CancellationTokenSource> -> ScheduleMessage<'a>)
union case Option.Some: Value: 'T -> Option<'T>
val x : TimeSpan
member MailboxProcessor.PostAndReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> 'Reply
More information