go
23 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package jobs
import (
"context"
"math/rand"
"time"
"github.com/robfig/cron/v3"
)
func Start(ctx context.Context, spec string, timeout time.Duration, fn func(context.Context) error) *cron.Cron {
c := cron.New()
c.AddFunc(spec, func() {
jitter := time.Duration(rand.Int63n(int64(2 * time.Second)))
time.Sleep(jitter)
runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
_ = fn(runCtx)
})
c.Start()
return c
}
1 file · go
Explain with highlit
Scheduled jobs get risky when deploys overlap or when jobs take longer than their interval. I use robfig/cron with a wrapper that creates a per-run context.WithTimeout, adds a bit of jitter to avoid synchronized load across instances, and logs start/finish. The jitter matters more than people think: without it, many pods run a cron at exactly the same second, which can spike a dependency. I also prefer idempotent jobs and, when needed, a distributed lock so only one instance does the work. The code below focuses on the core: wire the cron, add a wrapper that respects cancellation, and keep run durations bounded. In production you can add metrics (success/fail/duration) and alerts on repeated failures.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
ruby
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
rails
performance
streaming
by codesnips
3 tabs
go
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
go
aws
s3
by Leah Thompson
1 tab
go
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
go
http
client
by Leah Thompson
1 tab
Share this code
Here's the card — post it anywhere.