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

53 lines
1.6 KiB
Nim
Raw Normal View History

2023-07-13 14:07:04 +00:00
# SPDX-FileCopyrightText: ☭ Emery Hemingway
# SPDX-License-Identifier: Unlicense
2024-02-15 10:52:12 +00:00
import std/[asyncdispatch, monotimes, times, posix, times, epoll]
2023-07-13 14:07:04 +00:00
import preserves
2024-02-19 22:40:40 +00:00
import ../syndicate, ../protocols/timer
from ../protocols/dataspace import Observe
2023-07-13 14:07:04 +00:00
export timer
2023-12-31 17:15:06 +00:00
type Observe = dataspace.Observe
2023-07-13 14:07:04 +00:00
2024-02-15 10:52:12 +00:00
#[
proc timerfd_create(clock_id: ClockId, flags: cint): cint
{.importc: "timerfd_create", header: "<sys/timerfd.h>".}
proc timerfd_settime(ufd: cint, flags: cint,
utmr: var Itimerspec, otmr: var Itimerspec): cint
{.importc: "timerfd_settime", header: "<sys/timerfd.h>".}
proc eventfd(count: cuint, flags: cint): cint
{.importc: "eventfd", header: "<sys/eventfd.h>".}
]#
2023-07-13 14:07:04 +00:00
proc now: float64 = getTime().toUnixFloat()
2024-02-19 22:40:40 +00:00
proc spawnTimers*(ds: Cap): Actor {.discardable.} =
## Spawn a timer actor.
bootActor("timers") do (root: Facet):
let pat = inject(grab Observe(pattern: dropType LaterThan), {0: grabLit()})
#[
during(ds, pat) do (seconds: float):
let period = seconds - now()
if period < 0.001 or true:
let h = publish(ds, LaterThan(seconds: seconds).toPreserves)
]#
2024-02-15 10:52:12 +00:00
#[
else:
let fdi = timerfd_create(CLOCK_MONOTONIC, O_CLOEXEC or O_NONBLOCK)
2023-07-13 14:07:04 +00:00
2024-02-15 10:52:12 +00:00
addCallback(sleepAsync(period * 1_000), turn) do (turn: Turn):
2023-07-13 14:07:04 +00:00
discard publish(turn, ds, LaterThan(seconds: seconds))
2024-02-15 10:52:12 +00:00
]#
2024-02-19 22:40:40 +00:00
#[
proc after*(ds: Cap; dur: Duration; cb: proc () {.closure.}) =
2023-07-13 14:07:04 +00:00
## Execute `act` after some duration of time.
let later = now() + dur.inMilliseconds.float64 * 1_000.0
2024-02-15 10:52:12 +00:00
onPublish(ds, grab LaterThan(seconds: later)):
2024-02-19 22:40:40 +00:00
cb()
]#
# TODO: periodic timer