-
Notifications
You must be signed in to change notification settings - Fork 1
/
periodic.gleam
76 lines (62 loc) 路 1.67 KB
/
periodic.gleam
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
64
65
66
67
68
69
70
71
72
73
74
75
76
//// An actor that runs periodically.
import gleam/erlang/process.{type Subject}
import gleam/function.{identity}
import gleam/otp/actor
import gleam/result
import shakespeare.{type Thunk}
/// An interval of time.
pub type Interval {
/// An interval in milliseconds.
Ms(Int)
}
/// An actor that performs a given action periodically.
pub opaque type PeriodicActor {
PeriodicActor(subject: Subject(Message))
}
/// Starts a new `PeriodicActor` that executes the given function on the
/// specified interval.
pub fn start(
do do_work: Thunk,
every interval: Interval,
) -> Result(PeriodicActor, actor.StartError) {
actor.start_spec(actor.Spec(
init: fn() { init(interval, do_work) },
loop: loop,
init_timeout: 100,
))
|> result.map(PeriodicActor)
}
type Message {
Run
}
type State {
State(self: Subject(Message), interval: Interval, do_work: Thunk)
}
fn init(interval: Interval, do_work: Thunk) {
let subject = process.new_subject()
let state = State(subject, interval, do_work)
let selector =
process.new_selector()
|> process.selecting(subject, identity)
enqueue_first_run(state)
actor.Ready(state, selector)
}
fn loop(message: Message, state: State) -> actor.Next(Message, State) {
case message {
Run -> {
state.do_work()
enqueue_next_run(state)
actor.continue(state)
}
}
}
/// Enqueues the first run, to run immediately by the actor.
fn enqueue_first_run(state: State) -> Nil {
process.send(state.self, Run)
}
/// Enqueues the next run, to run after the actor's configured interval.
fn enqueue_next_run(state: State) -> Nil {
let Ms(interval) = state.interval
process.send_after(state.self, interval, Run)
Nil
}