Use Go Context Deadlines for Cron Job Safety
GoThe Problem
A Go cron job that hangs indefinitely blocks the next scheduled run and wastes resources. Without a deadline, there's no automatic timeout.
The Solution
Use context.WithDeadline or context.WithTimeout to enforce maximum execution time, and pair it with CronRabbit for external monitoring.
Context Deadlines as a Safety Net
Go's context package lets you set a maximum runtime. If your job exceeds the deadline, downstream operations (HTTP calls, DB queries) are cancelled automatically.
Combining with CronRabbit
If your job is killed by a context deadline, send a /fail ping before exiting. CronRabbit then alerts you that the job timed out, so you can investigate.
Code Examples
Context deadline with monitoring
Gopackage main
import (
"context"
"log"
"net/http"
"time"
)
func main() {
client := &http.Client{Timeout: 10 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
client.Get("https://ping.cronrabbit.com/your-id/start")
if err := runJobWithContext(ctx); err != nil {
if ctx.Err() == context.DeadlineExceeded {
log.Println("Job timed out")
}
client.Get("https://ping.cronrabbit.com/your-id/fail")
log.Fatal(err)
}
client.Get("https://ping.cronrabbit.com/your-id")
}