syndicate-nim/src/syndicate/actors/timers.nim

36 lines
1.1 KiB
Nim
Raw Normal View History

2023-07-13 14:07:04 +00:00
# SPDX-FileCopyrightText: ☭ Emery Hemingway
# SPDX-License-Identifier: Unlicense
import std/[asyncdispatch, monotimes, times]
import preserves
import syndicate
2023-07-13 14:07:04 +00:00
import ../protocols/timer
from syndicate/protocols/dataspace import Observe
export timer
2023-12-31 17:15:06 +00:00
type Observe = dataspace.Observe
2023-07-13 14:07:04 +00:00
proc now: float64 = getTime().toUnixFloat()
2023-07-24 15:13:36 +00:00
proc spawnTimers*(turn: var Turn; ds: Cap): Actor {.discardable.} =
2023-07-13 14:07:04 +00:00
## Spawn a timer actor.
spawn("timer", turn) do (turn: var Turn):
during(turn, ds, inject(grab Observe(pattern: dropType LaterThan), {0: grabLit()})) do (seconds: float):
2023-07-13 14:07:04 +00:00
let period = seconds - now()
if period < 0.001:
discard publish(turn, ds, LaterThan(seconds: seconds))
else:
addCallback(sleepAsync(period * 1_000), turn) do (turn: var Turn):
discard publish(turn, ds, LaterThan(seconds: seconds))
2023-07-13 14:07:04 +00:00
proc after*(turn: var Turn; ds: Cap; dur: Duration; act: TurnAction) =
2023-07-13 14:07:04 +00:00
## Execute `act` after some duration of time.
let later = now() + dur.inMilliseconds.float64 * 1_000.0
onPublish(turn, ds, grab LaterThan(seconds: later)):
act(turn)
# TODO: periodic timer