Go

time.Ticker — Periodic Tasks

admin by @admin ADMIN
16h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`time.NewTicker(d)` fires on a channel every `d` interval. Combine with select + a done channel for a clean way to run periodic work that can be cancelled.
Go
Raw
package main

import (
    "context"
    "fmt"
    "time"
)

func runPeriodic(ctx context.Context, interval time.Duration, work func()) {
    t := time.NewTicker(interval)
    defer t.Stop()                              // ALWAYS Stop the ticker

    for {
        select {
        case <-t.C:
            work()
        case <-ctx.Done():
            fmt.Println("stopping:", ctx.Err())
            return
        }
    }
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
    defer cancel()
    runPeriodic(ctx, 250*time.Millisecond, func() {
        fmt.Println("tick", time.Now().Format(time.TimeOnly))
    })
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.