A cron replacement in eighty lines of Go
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
- No overlap. The timer is reset only after the job returns, so a slow run delays the next one instead of stacking up.
- Jitter. Ten processes started together do not hit the database in the same second.
- Shutdown. The job receives the same context, so
SIGTERMfrom systemd stops it mid-way instead of being ignored.
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.