2023-04-19 12:27:16 +00:00
|
|
|
|
## An extension wrapper around nim-chronos
|
2024-06-28 10:34:57 +00:00
|
|
|
|
{.push raises: [].}
|
2023-04-12 11:05:34 +00:00
|
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
|
import chronos, chronicles
|
2023-04-19 12:27:16 +00:00
|
|
|
|
|
|
|
|
|
export chronos
|
2023-04-12 11:05:34 +00:00
|
|
|
|
|
2023-04-19 12:27:16 +00:00
|
|
|
|
## Extension methods
|
|
|
|
|
|
|
|
|
|
# Taken from: https://github.com/status-im/nim-libp2p/blob/master/libp2p/utils/heartbeat.nim
|
2023-04-12 11:05:34 +00:00
|
|
|
|
template heartbeat*(name: string, interval: Duration, body: untyped): untyped =
|
|
|
|
|
var nextHeartbeat = Moment.now()
|
|
|
|
|
while true:
|
|
|
|
|
body
|
|
|
|
|
|
|
|
|
|
nextHeartbeat += interval
|
|
|
|
|
let now = Moment.now()
|
|
|
|
|
if nextHeartbeat < now:
|
|
|
|
|
let
|
|
|
|
|
delay = now - nextHeartbeat
|
|
|
|
|
itv = interval
|
2023-04-19 12:27:16 +00:00
|
|
|
|
|
2023-04-12 11:05:34 +00:00
|
|
|
|
if delay > itv:
|
2024-03-15 23:08:47 +00:00
|
|
|
|
info "Missed multiple heartbeats",
|
|
|
|
|
heartbeat = name, delay = delay, hinterval = itv
|
2023-04-12 11:05:34 +00:00
|
|
|
|
else:
|
2023-04-19 12:27:16 +00:00
|
|
|
|
debug "Missed heartbeat", heartbeat = name, delay = delay, hinterval = itv
|
|
|
|
|
|
2023-04-12 11:05:34 +00:00
|
|
|
|
nextHeartbeat = now + itv
|
2023-04-19 12:27:16 +00:00
|
|
|
|
|
2023-04-12 11:05:34 +00:00
|
|
|
|
await sleepAsync(nextHeartbeat - now)
|