melkor-lab

A cron replacement in eighty lines of Go

· 3 min read

Most of my background jobs do not need cron syntax. They need “roughly every fifteen minutes, never two at once, and stop cleanly on shutdown”. That fits in a tiny loop.

func every(ctx context.Context, d time.Duration, job func(context.Context) error) {
    jitter := time.Duration(rand.Int63n(int64(d / 10)))
    t := time.NewTimer(jitter)
    defer t.Stop()
    for {
        select {
        case <-ctx.Done():
            return
        case <-t.C:
            if err := job(ctx); err != nil {
                slog.Error("job failed", "err", err)
            }
            t.Reset(d)
        }
    }
}

Why this shape

When to use the real thing

If a job must run at a wall-clock time, or must run even when the service is down, a systemd timer with Persistent=true is still the better tool. Everything else lives happily inside the process.