go
46 lines · 5 steps
A context-aware heartbeat ticker in Go
A small struct fires a callback on a fixed interval and stops cleanly when its context is cancelled.
Explained by
highlit
1package scheduler
2
3import (
4 "context"
5 "sync"
6 "time"
7)
8
9type Heartbeat struct {
10 mu sync.Mutex
11 ticker *time.Ticker
12 interval time.Duration
13 onTick func(time.Time)
14}
15
16func NewHeartbeat(interval time.Duration, onTick func(time.Time)) *Heartbeat {
17 return &Heartbeat{
18 interval: interval,
19 onTick: onTick,
20 }
21}
22
23func (h *Heartbeat) Run(ctx context.Context) {
24 h.mu.Lock()
25 h.ticker = time.NewTicker(h.interval)
26 h.mu.Unlock()
27 defer h.ticker.Stop()
28
29 for {
30 select {
31 case <-ctx.Done():
32 return
33 case t := <-h.ticker.C:
34 h.onTick(t)
35 }
36 }
37}
38
39func (h *Heartbeat) Reset(interval time.Duration) {
40 h.mu.Lock()
41 defer h.mu.Unlock()
42 h.interval = interval
43 if h.ticker != nil {
44 h.ticker.Reset(interval)
45 }
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A select over ctx.Done() and a ticker channel is the idiomatic way to run a cancellable periodic loop.
- 2Always defer ticker.Stop() so the underlying timer resources are released when the loop exits.
- 3Guarding shared fields with a mutex lets other goroutines safely reconfigure a running loop.
Related explainers
go
package api func RegisterRoutes(r *gin.Engine, deps *Dependencies) { r.GET("/health", func(c *gin.Context) {
Layering route groups and middleware in Gin
routing
middleware
authentication
Intermediate
8 steps
go
package payments import ( "context"
Fetching a charge over HTTP in Go
context-timeout
http-client
json-decoding
Intermediate
6 steps
go
package middleware import ( "compress/gzip"
How gzip response compression works in Gin
middleware
compression
http
Intermediate
8 steps
go
package middleware import ( "context"
Correlation ID tracing middleware in Gin
middleware
request tracing
structured logging
Intermediate
7 steps
go
package web import ( "embed"
Serving embedded static assets in Go
embed
static-assets
http-handler
Intermediate
8 steps
go
package pipeline import "sync"
The fan-in pattern in Go channels
concurrency
channels
fan-in
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-context-aware-heartbeat-ticker-in-go-explained-go-cbf0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.