actors/timers: use sleepAsync

The asyncdispatch.addTimer proc seems to leak file descriptors.
This commit is contained in:
Emery Hemingway 2024-01-14 12:11:31 +02:00
parent 6b642645f9
commit 75d1e33bff
1 changed files with 8 additions and 7 deletions

View File

@ -18,17 +18,18 @@ proc spawnTimers*(turn: var Turn; ds: Cap): Actor {.discardable.} =
## Spawn a timer actor.
spawn("timer", turn) do (turn: var Turn):
during(turn, ds, inject(grab Observe(pattern: dropType LaterThan), {0: grabLit()})) do (seconds: float64):
during(turn, ds, inject(grab Observe(pattern: dropType LaterThan), {0: grabLit()})) do (seconds: float):
let period = seconds - now()
if period < 0.001:
discard publish(turn, ds, LaterThan(seconds: seconds))
else:
let facet = turn.facet
addTimer(int(period * 1_000), oneshot = true) do (fd: AsyncFD) -> bool:
run(facet) do (turn: var Turn):
discard publish(turn, ds, LaterThan(seconds: seconds))
addCallback(sleepAsync(period * 1_000), turn) do (turn: var Turn):
discard publish(turn, ds, LaterThan(seconds: seconds))
template after*(turn: var Turn; ds: Cap; dur: Duration; act: untyped) =
proc after*(turn: var Turn; ds: Cap; dur: Duration; act: TurnAction) =
## Execute `act` after some duration of time.
let later = now() + dur.inMilliseconds.float64 * 1_000.0
onPublish(turn, ds, grab LaterThan(seconds: later), act)
onPublish(turn, ds, grab LaterThan(seconds: later)):
act(turn)
# TODO: periodic timer