heartbeatLoop runs heartbeatOnce at the interval specified by HeartbeatInterval until the lifecycle context is canceled.
()
| 281 | // heartbeatLoop runs heartbeatOnce at the interval specified by HeartbeatInterval |
| 282 | // until the lifecycle context is canceled. |
| 283 | func (s *server) heartbeatLoop() { |
| 284 | tick := time.NewTicker(time.Nanosecond) |
| 285 | defer tick.Stop() |
| 286 | for { |
| 287 | select { |
| 288 | case <-s.lifecycleCtx.Done(): |
| 289 | s.Logger.Debug(s.lifecycleCtx, "heartbeat loop canceled") |
| 290 | return |
| 291 | case <-tick.C: |
| 292 | if s.lifecycleCtx.Err() != nil { |
| 293 | return |
| 294 | } |
| 295 | start := s.timeNow() |
| 296 | hbCtx, hbCancel := context.WithTimeout(s.lifecycleCtx, s.heartbeatInterval) |
| 297 | if err := s.heartbeat(hbCtx); err != nil && !database.IsQueryCanceledError(err) { |
| 298 | s.Logger.Warn(hbCtx, "heartbeat failed", slog.Error(err)) |
| 299 | } |
| 300 | hbCancel() |
| 301 | elapsed := s.timeNow().Sub(start) |
| 302 | nextBeat := s.heartbeatInterval - elapsed |
| 303 | // avoid negative interval |
| 304 | if nextBeat <= 0 { |
| 305 | nextBeat = time.Nanosecond |
| 306 | } |
| 307 | tick.Reset(nextBeat) |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | // heartbeat updates the last seen at timestamp in the database. |
| 313 | // If HeartbeatFn is set, it will be called instead. |