2023-03-08 15:04:54 +00:00
|
|
|
## Nim-Codex
|
|
|
|
## Copyright (c) 2023 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
|
|
|
## Timer
|
|
|
|
## Used to execute a callback in a loop
|
|
|
|
|
|
|
|
import pkg/chronos
|
|
|
|
import pkg/upraises
|
|
|
|
|
2023-12-19 22:12:47 +00:00
|
|
|
import ../logutils
|
|
|
|
|
2023-03-08 15:04:54 +00:00
|
|
|
type
|
|
|
|
TimerCallback* = proc(): Future[void] {.gcsafe, upraises:[].}
|
|
|
|
Timer* = ref object of RootObj
|
|
|
|
callback: TimerCallback
|
|
|
|
interval: Duration
|
|
|
|
name: string
|
|
|
|
loopFuture: Future[void]
|
|
|
|
|
2023-06-22 15:11:18 +00:00
|
|
|
proc new*(T: type Timer, timerName = "Unnamed Timer"): Timer =
|
|
|
|
## Create a new Timer intance with the given name
|
|
|
|
Timer(name: timerName)
|
2023-03-08 15:04:54 +00:00
|
|
|
|
|
|
|
proc timerLoop(timer: Timer) {.async.} =
|
|
|
|
try:
|
|
|
|
while true:
|
|
|
|
await timer.callback()
|
|
|
|
await sleepAsync(timer.interval)
|
2023-04-19 13:06:00 +00:00
|
|
|
except CancelledError:
|
|
|
|
raise
|
2023-03-08 15:04:54 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
error "Timer caught unhandled exception: ", name=timer.name, msg=exc.msg
|
|
|
|
|
|
|
|
method start*(timer: Timer, callback: TimerCallback, interval: Duration) {.base.} =
|
|
|
|
if timer.loopFuture != nil:
|
|
|
|
return
|
|
|
|
trace "Timer starting: ", name=timer.name
|
|
|
|
timer.callback = callback
|
|
|
|
timer.interval = interval
|
|
|
|
timer.loopFuture = timerLoop(timer)
|
|
|
|
|
|
|
|
method stop*(timer: Timer) {.async, base.} =
|
|
|
|
if timer.loopFuture != nil:
|
|
|
|
trace "Timer stopping: ", name=timer.name
|
|
|
|
await timer.loopFuture.cancelAndWait()
|
|
|
|
timer.loopFuture = nil
|